Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
refactor(webui): separate presentation views and expand component gallery (#6179)
chengyongru30e43aec822b
diff --git a/Dockerfile b/Dockerfileindex 4b64e9692..4c411e410 100644--- a/Dockerfile+++ b/Dockerfile@@ -6,6 +6,7 @@ WORKDIR /app/webuiRUN npm ciCOPY webui/ ./COPY packages/client-events/ /app/packages/client-events/+COPY nanobot/channels/ /app/nanobot/channels/RUN mkdir -p /app/nanobot/web && npm run buildFROM ghcr.io/astral-sh/uv:python3.12-bookworm-slimdiff --git a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsxindex 2a243471e..bff423bc7 100644--- a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx+++ b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx@@ -1,14 +1,6 @@-import { useTranslation } from "react-i18next";--import {- channelTranslator,-} from "@/channel-plugins/i18n";import type { ChannelPluginPanelProps } from "@/channel-plugins/types";import { ChannelInstancesPanel } from "@/components/settings/channels/ChannelInstancesPanel";-import type {- NanobotChannelInstanceInfo,- NanobotFeatureInfo,-} from "@/lib/types";+import { FeishuAssistantsPanelView } from "./FeishuAssistantsPanelView";import { FeishuConnectFlow } from "./FeishuConnectFlow";export function FeishuAssistantsPanel({@@ -17,60 +9,17 @@ export function FeishuAssistantsPanel({showBrandLogos,onFeaturesUpdate,}: ChannelPluginPanelProps) {- const { t } = useTranslation();- const tx = channelTranslator(t, "feishu");- const instances = feature.instances?.length- ? feature.instances- : [defaultFeishuInstance(feature)];-- return (- <ChannelInstancesPanel- feature={feature}- showBrandLogos={showBrandLogos}- instances={instances}- onFeaturesUpdate={onFeaturesUpdate}- customization={{- toggleAriaLabel: (instance) => tx("custom.toggleAssistant", "{{name}} assistant", {- name: instanceDisplayName(instance),- }),- configuredLabel: tx("custom.configured", "Connected"),- needsSetupLabel: tx("custom.needsSetup", "Needs authorization"),- renderInstanceSummary: () => null,- renderInstanceAction: (instance) => instance.configured ? null : (- <FeishuConnectFlow- key={instance.id}- token={token}- instanceId={instance.id}- mode="replace"- idleLabel={t("settings.channels.connect", { defaultValue: "Connect" })}- onFeaturesUpdate={onFeaturesUpdate}- />- ),- footer: instances.some((instance) => instance.configured) ? (- <FeishuConnectFlow- key={instances.map((instance) => instance.id).join(",")}- token={token}- mode="create"- idleLabel={tx("custom.addAssistant", "Add another assistant")}- onFeaturesUpdate={onFeaturesUpdate}- />- ) : null,- }}- />- );-}--function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInstanceInfo {- return {- id: "default",- name: "nanobot",- enabled: feature.enabled,- configured: Boolean(feature.configured),- config_values: feature.config_values ?? {},- configured_fields: feature.configured_fields ?? [],- };-}--function instanceDisplayName(instance: NanobotChannelInstanceInfo): string {- return instance.display_name?.trim() || instance.name.trim() || instance.id;+ return <ChannelInstancesPanel+ feature={feature}+ showBrandLogos={showBrandLogos}+ onFeaturesUpdate={onFeaturesUpdate}+ renderView={(props) => <FeishuAssistantsPanelView+ {...props}+ renderConnectFlow={(options) => <FeishuConnectFlow+ {...options}+ token={token}+ onFeaturesUpdate={onFeaturesUpdate}+ />}+ />}+ />;}diff --git a/nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsx b/nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsxnew file mode 100644index 000000000..a8185fc67--- /dev/null+++ b/nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsx@@ -0,0 +1,75 @@+import { Fragment, type ReactNode } from "react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { ChannelInstancesPanelView, type ChannelInstancesPanelViewProps } from "@/components/settings/channels/ChannelInstancesPanelView";+import type { NanobotChannelInstanceInfo, NanobotFeatureInfo } from "@/lib/types";++export type FeishuConnectOptions = {+ instanceId?: string;+ mode: "replace" | "create";+ idleLabel: string;+};++export type FeishuAssistantsPanelViewProps = Omit<ChannelInstancesPanelViewProps, "customization"> & {+ renderConnectFlow: (options: FeishuConnectOptions) => ReactNode;+};++export function FeishuAssistantsPanelView({+ feature,+ showBrandLogos,+ instances: providedInstances,+ onToggleInstance,+ onSaveInstance,+ renderConnectFlow,+}: FeishuAssistantsPanelViewProps) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "feishu");+ const instances = providedInstances ?? (feature.instances?.length+ ? feature.instances+ : [defaultFeishuInstance(feature)]);++ return <ChannelInstancesPanelView+ feature={feature}+ showBrandLogos={showBrandLogos}+ instances={instances}+ onToggleInstance={onToggleInstance}+ onSaveInstance={onSaveInstance}+ customization={{+ toggleAriaLabel: (instance) => tx("custom.toggleAssistant", "{{name}} assistant", {+ name: instanceDisplayName(instance),+ }),+ configuredLabel: tx("custom.configured", "Connected"),+ needsSetupLabel: tx("custom.needsSetup", "Needs authorization"),+ renderInstanceSummary: () => null,+ renderInstanceAction: (instance) => instance.configured ? null : (+ <Fragment key={instance.id}>{renderConnectFlow({+ instanceId: instance.id,+ mode: "replace",+ idleLabel: t("settings.channels.connect", { defaultValue: "Connect" }),+ })}</Fragment>+ ),+ footer: instances.some((instance) => instance.configured) ? (+ <Fragment key={instances.map((instance) => instance.id).join(",")}>{renderConnectFlow({+ mode: "create",+ idleLabel: tx("custom.addAssistant", "Add another assistant"),+ })}</Fragment>+ ) : null,+ }}+ />;+}++function defaultFeishuInstance(feature: NanobotFeatureInfo): NanobotChannelInstanceInfo {+ return {+ id: "default",+ name: "nanobot",+ enabled: feature.enabled,+ configured: Boolean(feature.configured),+ config_values: feature.config_values ?? {},+ configured_fields: feature.configured_fields ?? [],+ };+}++function instanceDisplayName(instance: NanobotChannelInstanceInfo): string {+ return instance.display_name?.trim() || instance.name.trim() || instance.id;+}diff --git a/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx b/nanobot/channels/feishu/webui/FeishuConnectFlow.tsxindex 471a57bc0..85bac0ecc 100644--- a/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx+++ b/nanobot/channels/feishu/webui/FeishuConnectFlow.tsx@@ -1,9 +1,8 @@-import { useTranslation } from "react-i18next";--import { channelTranslator } from "@/channel-plugins/i18n";import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";import type { NanobotFeaturesPayload } from "@/lib/types";+import { FeishuConnectFlowView, useFeishuConnectLabels } from "./FeishuConnectFlowView";+export function FeishuConnectFlow({token,instanceId = "default",@@ -19,8 +18,7 @@ export function FeishuConnectFlow({connectRequestId?: number;onFeaturesUpdate: (payload: NanobotFeaturesPayload) => void;}) {- const { t } = useTranslation();- const tx = channelTranslator(t, "feishu");+ const labels = useFeishuConnectLabels();return (<ChannelQrConnectFlowtoken={token}@@ -29,20 +27,8 @@ export function FeishuConnectFlow({idleLabel={idleLabel}connectRequestId={connectRequestId}onFeaturesUpdate={onFeaturesUpdate}- labels={{- qrAlt: tx("custom.qrAlt", "Feishu connection QR code"),- scanTitle: tx("custom.scanTitle", "Scan with Feishu"),- scanDescription: tx(- "custom.scanDescription",- "Use Feishu or Lark on your phone to scan this code. nanobot will finish setup automatically after authorization.",- ),- waiting: tx("custom.waiting", "Waiting for authorization..."),- connected: tx("custom.connected", "Feishu is connected."),- stopped: tx("custom.stopped", "Connection stopped."),- connecting: tx("custom.connecting", "Connecting..."),- scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),- connect: t("settings.channels.connect", { defaultValue: "Connect" }),- }}+ labels={labels}+ renderView={(props) => <FeishuConnectFlowView {...props} />}/>);}diff --git a/nanobot/channels/feishu/webui/FeishuConnectFlowView.tsx b/nanobot/channels/feishu/webui/FeishuConnectFlowView.tsxnew file mode 100644index 000000000..b2f07a032--- /dev/null+++ b/nanobot/channels/feishu/webui/FeishuConnectFlowView.tsx@@ -0,0 +1,30 @@+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";++export type FeishuConnectFlowViewProps = Omit<ChannelQrConnectFlowViewProps, "labels">;++export function useFeishuConnectLabels(): ChannelQrConnectLabels {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "feishu");+ return {+ qrAlt: tx("custom.qrAlt", "Feishu connection QR code"),+ scanTitle: tx("custom.scanTitle", "Scan with Feishu"),+ scanDescription: tx(+ "custom.scanDescription",+ "Use Feishu or Lark on your phone to scan this code. nanobot will finish setup automatically after authorization.",+ ),+ waiting: tx("custom.waiting", "Waiting for authorization..."),+ connected: tx("custom.connected", "Feishu is connected."),+ stopped: tx("custom.stopped", "Connection stopped."),+ connecting: tx("custom.connecting", "Connecting..."),+ scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),+ connect: t("settings.channels.connect", { defaultValue: "Connect" }),+ };+}++export function FeishuConnectFlowView(props: FeishuConnectFlowViewProps) {+ const labels = useFeishuConnectLabels();+ return <ChannelQrConnectFlowView {...props} labels={labels} />;+}diff --git a/nanobot/channels/linear/webui/LinearConnectFlow.tsx b/nanobot/channels/linear/webui/LinearConnectFlow.tsxindex 04b9a589a..42e07d44d 100644--- a/nanobot/channels/linear/webui/LinearConnectFlow.tsx+++ b/nanobot/channels/linear/webui/LinearConnectFlow.tsx@@ -1,12 +1,12 @@-import { useCallback, useRef, type ReactNode } from "react";-import { ExternalLink } from "lucide-react";+import type { ReactNode } from "react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";-import { Button } from "@/components/ui/button";import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";+import { LinearConnectFlowView, linearConnectLabels } from "./LinearConnectFlowView";+export function LinearConnectFlow({token,feature,@@ -23,62 +23,10 @@ export function LinearConnectFlow({}) {const { t } = useTranslation();const tx = channelTranslator(t, "linear");- const flowRef = useRef<HTMLDivElement | null>(null);- const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => {- if (!link) return;- flowRef.current?.scrollIntoView({ block: "nearest" });- link.focus({ preventScroll: true });- }, []);-- return (- <div ref={flowRef} className="mt-3 space-y-3">- <ChannelQrConnectFlow- token={token}- channelName="linear"- idleLabel={idleLabel}- connectRequestId={connectRequestId}- startParams={connectRequestId ? { force: true } : undefined}- forceOnRepeat- showQrCode={false}- connected={connected}- suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"}- onFeaturesUpdate={onFeaturesUpdate}- onActiveChange={onActiveChange}- renderActions={renderActions}- labels={{- scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),- scanDescription: tx(- "custom.authorizeDescription",- "Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done.",- ),- waiting: tx("custom.waiting", "Waiting for Linear authorization..."),- connected: tx("custom.connected", "Linear is connected."),- stopped: tx("custom.stopped", "Authorization stopped."),- connecting: tx("custom.connecting", "Connecting..."),- scanAgain: tx("custom.reauthorize", "Reauthorize"),- connect: tx("custom.connect", "Connect Linear"),- }}- renderPending={({ connect }) => (- <div className="mt-3 space-y-3">- <div className="flex items-center gap-2 text-[12px] text-muted-foreground">- <span className="h-2 w-2 animate-pulse rounded-full bg-[#5E6AD2] motion-reduce:animate-none" aria-hidden />- {tx("custom.waiting", "Waiting for Linear authorization...")}- </div>- {connect.qr_url ? (- <Button- asChild- size="sm"- className="h-8 rounded-full px-3 text-[12px] font-semibold"- >- <a ref={revealAuthorization} href={connect.qr_url} target="_blank" rel="noreferrer">- <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />- {tx("custom.openLinear", "Continue in Linear")}- </a>- </Button>- ) : null}- </div>- )}- />- </div>- );+ return <ChannelQrConnectFlow token={token} channelName="linear" idleLabel={idleLabel}+ connectRequestId={connectRequestId} startParams={connectRequestId ? { force: true } : undefined}+ forceOnRepeat showQrCode={false} connected={connected}+ suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"}+ onFeaturesUpdate={onFeaturesUpdate} onActiveChange={onActiveChange} renderActions={renderActions}+ labels={linearConnectLabels(tx)} renderView={(props) => <LinearConnectFlowView {...props} />} />;}diff --git a/nanobot/channels/linear/webui/LinearConnectFlowView.tsx b/nanobot/channels/linear/webui/LinearConnectFlowView.tsxnew file mode 100644index 000000000..5f11c2fae--- /dev/null+++ b/nanobot/channels/linear/webui/LinearConnectFlowView.tsx@@ -0,0 +1,58 @@+import { useCallback, useRef } from "react";+import { ExternalLink } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";+import { Button } from "@/components/ui/button";++export function linearConnectLabels(tx: ReturnType<typeof channelTranslator>): ChannelQrConnectLabels {+ return {+ scanTitle: tx("custom.authorizeTitle", "Authorize in Linear"),+ scanDescription: tx("custom.authorizeDescription", "Continue in Linear to choose a workspace and authorize nanobot. Return here when you're done."),+ waiting: tx("custom.waiting", "Waiting for Linear authorization..."),+ connected: tx("custom.connected", "Linear is connected."),+ stopped: tx("custom.stopped", "Authorization stopped."),+ connecting: tx("custom.connecting", "Connecting..."),+ scanAgain: tx("custom.reauthorize", "Reauthorize"),+ connect: tx("custom.connect", "Connect Linear"),+ };+}++export function LinearConnectFlowView(props: ChannelQrConnectFlowViewProps) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const flowRef = useRef<HTMLDivElement | null>(null);+ const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => {+ if (!link) return;+ flowRef.current?.scrollIntoView({ block: "nearest" });+ link.focus({ preventScroll: true });+ }, []);++ return (+ <div ref={flowRef} className="mt-3 space-y-3">+ <ChannelQrConnectFlowView {...props} showQrCode={false}+ renderPending={({ connect }) => (+ <div className="mt-3 space-y-3">+ <div className="flex items-center gap-2 text-[12px] text-muted-foreground">+ <span className="h-2 w-2 animate-pulse rounded-full bg-[#5E6AD2] motion-reduce:animate-none" aria-hidden />+ {tx("custom.waiting", "Waiting for Linear authorization...")}+ </div>+ {connect.qr_url ? (+ <Button+ asChild+ size="sm"+ className="h-8 rounded-full px-3 text-[12px] font-semibold"+ >+ <a ref={revealAuthorization} href={connect.qr_url} target="_blank" rel="noreferrer">+ <ExternalLink className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ {tx("custom.openLinear", "Continue in Linear")}+ </a>+ </Button>+ ) : null}+ </div>+ )}+ />+ </div>+ );+}diff --git a/nanobot/channels/linear/webui/LinearMemberAccess.tsx b/nanobot/channels/linear/webui/LinearMemberAccess.tsxindex aa87f73b3..b90397dea 100644--- a/nanobot/channels/linear/webui/LinearMemberAccess.tsx+++ b/nanobot/channels/linear/webui/LinearMemberAccess.tsx@@ -1,19 +1,9 @@-import { useEffect, useId, useState, useSyncExternalStore } from "react";-import { Check, ChevronDown, Info, RefreshCw, Search } from "lucide-react";-import { useTranslation } from "react-i18next";+import { useSyncExternalStore } from "react";-import { channelTranslator } from "@/channel-plugins/i18n";-import { ToggleButton } from "@/components/settings/ToggleButton";-import { SETTINGS_SEARCH_INPUT_CLASS, SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";-import { SettingsHint } from "@/components/settings/shared/SettingsHint";-import { Button } from "@/components/ui/button";-import { DisclosureContent } from "@/components/ui/disclosure";-import { SearchInput } from "@/components/ui/input";-import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";import { linearMemberAccessStore } from "./member-access-store";-import { LinearAvatar } from "./LinearAvatar";+import { LinearMemberAccessView } from "./LinearMemberAccessView";export function LinearMemberAccess({ organizationId, configScope = "", disabled = false }: {organizationId: string;@@ -21,115 +11,8 @@ export function LinearMemberAccess({ organizationId, configScope = "", disableddisabled?: boolean;}) {const { client, token } = useClient();- const { t } = useTranslation();- const tx = channelTranslator(t, "linear");- const panelId = useId();- const [expanded, setExpanded] = useState(false);- const [search, setSearch] = useState("");const store = linearMemberAccessStore(client, token, configScope, organizationId);- const { payload, loading, error, saves } = useSyncExternalStore(store.subscribe, store.getSnapshot);- const members = payload?.members ?? [];- const saving = Object.values(saves).some((save) => save.status === "saving");-- useEffect(() => {- if (expanded && !disabled) void store.load();- }, [store, expanded, disabled]);-- const prefetch = () => { if (!disabled) void store.load(); };- const needle = search.trim().toLocaleLowerCase();- const visible = members.filter((member) => [member.name, member.id]- .some((value) => value.toLocaleLowerCase().includes(needle)));- const names = new Set<string>();- const duplicateNames = new Set<string>();- for (const member of members) {- if (names.has(member.name)) duplicateNames.add(member.name);- names.add(member.name);- }-- return (- <section className="w-full border-t border-border/50 bg-settings-surface">- <button type="button" aria-expanded={expanded} aria-controls={panelId}- disabled={disabled} onMouseEnter={prefetch} onFocus={prefetch}- className="settings-list-inset flex min-h-12 w-full items-center justify-between gap-3 py-2 text-start text-[12px] font-medium settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"- onClick={() => setExpanded(!expanded)}>- <span className="shrink-0">{tx("members.title", "Member access")}</span>- <span className="flex min-w-0 items-center gap-2">- <span role="status" aria-live="polite" className="text-end text-[11px] font-normal text-muted-foreground">- {payload ? !expanded ? tx("members.summary", "{{allowed}} enabled", {- allowed: members.filter((member) => member.allowed).length,- }) : null : loading ? tx("members.loading", "Finding members…") : null}- </span>- <ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none", expanded && "rotate-180")} aria-hidden />- </span>- </button>- <span role="status" aria-live="polite" className="sr-only">- {payload && loading ? tx("members.refreshing", "Checking for updates…") : null}- </span>- <DisclosureContent id={panelId} open={expanded} className="space-y-3 pb-2">- {payload?.legacy_allow_all ? <p className="settings-list-inset rounded-control bg-muted py-2 text-[12px] leading-5">- {tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")}- </p> : null}- <div className="settings-list-inset flex items-center gap-2">- <div className="relative min-w-0 flex-1">- <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />- <SearchInput value={search} onChange={(event) => setSearch(event.target.value)}- aria-label={tx("members.search", "Search members")}- placeholder={tx("members.search", "Search members")}- className={cn(SETTINGS_SEARCH_INPUT_CLASS, "pl-9 text-[13px]")} />- </div>- <Button type="button" variant="ghost" size="icon" disabled={disabled || loading || saving}- onClick={() => void store.load(true)} aria-label={tx("members.refresh", "Refresh members")}- title={tx("members.refresh", "Refresh members")}>- <RefreshCw className="h-4 w-4 text-muted-foreground" aria-hidden />- </Button>- <SettingsHint description={tx("members.help", "Enable members to use nanobot without a pairing code. Linear's existing authorization still applies. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")}>- <span className="flex h-9 w-9 items-center justify-center text-muted-foreground">- <Info className="h-4 w-4" aria-hidden />- <span className="sr-only">{tx("members.details", "About member access")}</span>- </span>- </SettingsHint>- </div>- {error ? <p role="alert" className="settings-list-inset break-words text-[12px] leading-5 text-destructive">- {error} {tx("members.retry", "Refresh members to check the current state and try again.")}- </p> : null}- {payload && !error && visible.length === 0 ? <p className="settings-list-inset py-3 text-[12px] text-muted-foreground">- {tx("members.empty", "No matching active members.")}- </p> : null}- <SettingsGroup>- <ul className="max-h-80 overflow-y-auto" aria-label={tx("members.title", "Member access")}>- {visible.map((member) => {- const save = saves[member.id];- const statusId = `${panelId}-${member.id}-status`;- return <li key={member.id}>- <SettingsRow title={<div className="flex min-w-0 items-center gap-3">- <LinearAvatar name={member.name} url={member.avatar_url} />- <div className="min-w-0">- <p className="truncate" title={member.id}>{member.name}</p>- <div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal leading-4 text-muted-foreground">- <span id={save?.status === "error" ? undefined : statusId} role="status" aria-live="polite" className="inline-flex items-center gap-1">- {save?.status === "saving" ? tx("members.working", "Saving…") : null}- {save?.status === "saved" ? <><Check className="h-3 w-3" aria-hidden />{tx("members.saved", "Saved")}</> : null}- </span>- </div>- {duplicateNames.has(member.name) ?- <p className="break-all text-[11px] font-normal text-muted-foreground">{member.id}</p> : null}- </div>- </div>}>- <ToggleButton checked={member.allowed}- disabled={disabled || save?.status === "saving" || save?.status === "error"}- aria-describedby={save ? statusId : undefined} aria-invalid={save?.status === "error" || undefined}- label={tx("members.allow", "Allow {{name}} to use nanobot", { name: member.name })}- onChange={(allowed) => void store.setAllowed(member.id, allowed,- tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."))} />- </SettingsRow>- {save?.status === "error" ? <p id={statusId} role="alert" className="settings-list-inset break-words pb-3 text-[12px] leading-5 text-destructive">- {save.message} {tx("members.retry", "Refresh members to check the current state and try again.")}- </p> : null}- </li>;- })}- </ul>- </SettingsGroup>- </DisclosureContent>- </section>- );+ const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot);+ return <LinearMemberAccessView snapshot={snapshot} disabled={disabled}+ onLoad={store.load} onSetAllowed={store.setAllowed} />;}diff --git a/nanobot/channels/linear/webui/LinearMemberAccessView.tsx b/nanobot/channels/linear/webui/LinearMemberAccessView.tsxnew file mode 100644index 000000000..3652d196b--- /dev/null+++ b/nanobot/channels/linear/webui/LinearMemberAccessView.tsx@@ -0,0 +1,142 @@+import { useEffect, useId, useState } from "react";+import { Check, ChevronDown, Info, RefreshCw, Search } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { ToggleButton } from "@/components/ui/toggle-button";+import { SETTINGS_SEARCH_INPUT_CLASS, SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";+import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { Button } from "@/components/ui/button";+import { DisclosureContent } from "@/components/ui/disclosure";+import { SearchInput } from "@/components/ui/input";+import { cn } from "@/lib/utils";++import { LinearAvatar } from "./LinearAvatar";++import type { LinearMembersPayload } from "./types";++export type LinearMemberSave = { status: "saving" | "saved" } | { status: "error"; message: string };+export interface LinearMemberAccessSnapshot {+ payload: LinearMembersPayload | null;+ loading: boolean;+ error: string | null;+ saves: Record<string, LinearMemberSave>;+}++export function LinearMemberAccessView({ snapshot, disabled = false, onLoad, onSetAllowed }: {+ snapshot: LinearMemberAccessSnapshot;+ disabled?: boolean;+ onLoad: (force?: boolean) => void;+ onSetAllowed: (userId: string, allowed: boolean, unconfirmedMessage: string) => void;+}) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const panelId = useId();+ const [expanded, setExpanded] = useState(false);+ const [search, setSearch] = useState("");+ const { payload, loading, error, saves } = snapshot;+ const members = payload?.members ?? [];+ const saving = Object.values(saves).some((save) => save.status === "saving");++ useEffect(() => {+ if (expanded && !disabled) onLoad();+ }, [onLoad, expanded, disabled]);++ const prefetch = () => { if (!disabled) onLoad(); };+ const needle = search.trim().toLocaleLowerCase();+ const visible = members.filter((member) => [member.name, member.id]+ .some((value) => value.toLocaleLowerCase().includes(needle)));+ const names = new Set<string>();+ const duplicateNames = new Set<string>();+ for (const member of members) {+ if (names.has(member.name)) duplicateNames.add(member.name);+ names.add(member.name);+ }++ return (+ <section className="w-full border-t border-border/50 bg-settings-surface">+ <button type="button" aria-expanded={expanded} aria-controls={panelId}+ disabled={disabled} onMouseEnter={prefetch} onFocus={prefetch}+ className="settings-list-inset flex min-h-12 w-full items-center justify-between gap-3 py-2 text-start text-[12px] font-medium settings-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"+ onClick={() => setExpanded(!expanded)}>+ <span className="shrink-0">{tx("members.title", "Member access")}</span>+ <span className="flex min-w-0 items-center gap-2">+ <span role="status" aria-live="polite" className="text-end text-[11px] font-normal text-muted-foreground">+ {payload ? !expanded ? tx("members.summary", "{{allowed}} enabled", {+ allowed: members.filter((member) => member.allowed).length,+ }) : null : loading ? tx("members.loading", "Finding members…") : null}+ </span>+ <ChevronDown className={cn("h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200 motion-reduce:transition-none", expanded && "rotate-180")} aria-hidden />+ </span>+ </button>+ <span role="status" aria-live="polite" className="sr-only">+ {payload && loading ? tx("members.refreshing", "Checking for updates…") : null}+ </span>+ <DisclosureContent id={panelId} open={expanded} className="space-y-3 pb-2">+ {payload?.legacy_allow_all ? <p className="settings-list-inset rounded-control bg-muted py-2 text-[12px] leading-5">+ {tx("members.allowAll", "Advanced settings currently allow all members (*), including new members. Individual off switches still take precedence. Remove * to require approval for new members.")}+ </p> : null}+ <div className="settings-list-inset flex items-center gap-2">+ <div className="relative min-w-0 flex-1">+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" aria-hidden />+ <SearchInput value={search} onChange={(event) => setSearch(event.target.value)}+ aria-label={tx("members.search", "Search members")}+ placeholder={tx("members.search", "Search members")}+ className={cn(SETTINGS_SEARCH_INPUT_CLASS, "pl-9 text-[13px]")} />+ </div>+ <Button type="button" variant="ghost" size="icon" disabled={disabled || loading || saving}+ onClick={() => onLoad(true)} aria-label={tx("members.refresh", "Refresh members")}+ title={tx("members.refresh", "Refresh members")}>+ <RefreshCw className="h-4 w-4 text-muted-foreground" aria-hidden />+ </Button>+ <SettingsHint description={tx("members.help", "Enable members to use nanobot without a pairing code. Linear's existing authorization still applies. This does not grant access to the nanobot admin UI. Turning access off blocks new requests, not tasks already running.")}>+ <span className="flex h-9 w-9 items-center justify-center text-muted-foreground">+ <Info className="h-4 w-4" aria-hidden />+ <span className="sr-only">{tx("members.details", "About member access")}</span>+ </span>+ </SettingsHint>+ </div>+ {error ? <p role="alert" className="settings-list-inset break-words text-[12px] leading-5 text-destructive">+ {error} {tx("members.retry", "Refresh members to check the current state and try again.")}+ </p> : null}+ {payload && !error && visible.length === 0 ? <p className="settings-list-inset py-3 text-[12px] text-muted-foreground">+ {tx("members.empty", "No matching active members.")}+ </p> : null}+ <SettingsGroup>+ <ul className="max-h-80 overflow-y-auto" aria-label={tx("members.title", "Member access")}>+ {visible.map((member) => {+ const save = saves[member.id];+ const statusId = `${panelId}-${member.id}-status`;+ return <li key={member.id}>+ <SettingsRow title={<div className="flex min-w-0 items-center gap-3">+ <LinearAvatar name={member.name} url={member.avatar_url} />+ <div className="min-w-0">+ <p className="truncate" title={member.id}>{member.name}</p>+ <div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal leading-4 text-muted-foreground">+ <span id={save?.status === "error" ? undefined : statusId} role="status" aria-live="polite" className="inline-flex items-center gap-1">+ {save?.status === "saving" ? tx("members.working", "Saving…") : null}+ {save?.status === "saved" ? <><Check className="h-3 w-3" aria-hidden />{tx("members.saved", "Saved")}</> : null}+ </span>+ </div>+ {duplicateNames.has(member.name) ?+ <p className="break-all text-[11px] font-normal text-muted-foreground">{member.id}</p> : null}+ </div>+ </div>}>+ <ToggleButton checked={member.allowed}+ disabled={disabled || save?.status === "saving" || save?.status === "error"}+ aria-describedby={save ? statusId : undefined} aria-invalid={save?.status === "error" || undefined}+ label={tx("members.allow", "Allow {{name}} to use nanobot", { name: member.name })}+ onChange={(allowed) => onSetAllowed(member.id, allowed,+ tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."))} />+ </SettingsRow>+ {save?.status === "error" ? <p id={statusId} role="alert" className="settings-list-inset break-words pb-3 text-[12px] leading-5 text-destructive">+ {save.message} {tx("members.retry", "Refresh members to check the current state and try again.")}+ </p> : null}+ </li>;+ })}+ </ul>+ </SettingsGroup>+ </DisclosureContent>+ </section>+ );+}diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsxindex ce96289da..f1d37cefb 100644--- a/nanobot/channels/linear/webui/LinearPanel.tsx+++ b/nanobot/channels/linear/webui/LinearPanel.tsx@@ -1,61 +1,24 @@-import { useCallback, useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from "react";-import { AlertCircle, Check, ChevronDown, ExternalLink, Info, Loader2, MoreHorizontal, Plus, RefreshCw, Unplug } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";import type { ChannelPluginPanelProps } from "@/channel-plugins/types";-import {- CredentialForm,- channelFieldInputId,- channelValuesForSubmit,- defaultChannelFieldValues,-} from "@/components/settings/channels/CredentialForm";-import {- CHANNEL_SETUP_PANEL_CLASS_NAME,- ChannelLogo,- ChannelRuntimeError,- channelSetup,- localizedChannelDisplayName,-} from "@/components/settings/channels/ChannelIdentity";-import { Button } from "@/components/ui/button";-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,-} from "@/components/ui/dropdown-menu";-import {- AlertDialog,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,-} from "@/components/ui/alert-dialog";-import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";+import { channelValuesForSubmit, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";+import { channelSetup } from "@/components/settings/channels/ChannelIdentity";import { useAutoSave } from "@/components/settings/shared/useAutoSave";-import { SettingsHint } from "@/components/settings/shared/SettingsHint";import { configureChannel, disableNanobotFeature, fetchNanobotFeatures } from "@/lib/api";-import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";import { manageLinearWorkspace } from "./api";import type { LinearInstallationSummary } from "./types";import { LinearConnectFlow } from "./LinearConnectFlow";import { LinearMemberAccess } from "./LinearMemberAccess";-import { LinearAvatar } from "./LinearAvatar";-import { linearManifestUrl } from "./manifest";import { linearWorkspaceStore } from "./workspace-store";import { linearMemberAccessStore } from "./member-access-store";import { LinearResetConnection } from "./LinearResetConnection";-import { LinearSecretField } from "./LinearSecretField";+import { LinearPanelView } from "./LinearPanelView";const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";-const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";-const CALLBACK_PATH_KEY = "channels.linear.oauthCallbackPath";-export function LinearPanel({token,feature,@@ -68,7 +31,6 @@ export function LinearPanel({const { client } = useClient();const { t, i18n } = useTranslation();const tx = channelTranslator(t, "linear");- const displayName = localizedChannelDisplayName(feature, t);const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);const fields = setup.fields ?? [];const advancedFields = setup.manualFields ?? [];@@ -84,7 +46,6 @@ export function LinearPanel({const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());- const [advancedOpen, setAdvancedOpen] = useState(false);const [saving, setSaving] = useState(false);const [resetting, setResetting] = useState(false);const [connecting, setConnecting] = useState(false);@@ -92,7 +53,6 @@ export function LinearPanel({const [connectionGeneration, setConnectionGeneration] = useState(0);const [notice, setNotice] = useState<string | null>(null);const [saved, setSaved] = useState(false);- const [publicUrlPromptOpen, setPublicUrlPromptOpen] = useState(false);const workspaceStore = linearWorkspaceStore(client, token, JSON.stringify([feature.config_values?.["channels.linear.clientId"],feature.config_values?.[PUBLIC_BASE_URL_KEY],@@ -101,15 +61,10 @@ export function LinearPanel({error: inspectionError } = useSyncExternalStore(workspaceStore.subscribe, workspaceStore.getSnapshot);const installations = cachedInstallations ?? [];const [disconnectingId, setDisconnectingId] = useState<string | null>(null);- const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);const [workspaceNotice, setWorkspaceNotice] = useState<string | null>(null);const [workspaceError, setWorkspaceError] = useState<string | null>(null);- const workspaceActionRef = useRef<HTMLButtonElement | null>(null);- const skipMenuRestoreFocus = useRef(false);- const disconnectTarget = installations.find(item => item.organization_id === disconnectConfirmId);const savePromiseRef = useRef<Promise<boolean> | null>(null);const secretSavePromiseRef = useRef<Promise<void> | null>(null);- const advancedPanelId = useId();useEffect(() => {setFieldValues(defaultChannelFieldValues(editableFields, feature.config_values));@@ -127,7 +82,6 @@ export function LinearPanel({const touchedSecret = secretFields.some((field) =>touchedFields.has(field.key) && Boolean(fieldValues[field.key]?.trim()),);- const hasSavedSecrets = secretFields.some((field) => configuredFields.has(field.key));const memberConfigScope = JSON.stringify([feature.config_values?.["channels.linear.clientId"],feature.config_values?.["channels.linear.allowFrom"],@@ -135,23 +89,9 @@ export function LinearPanel({const forgetWorkspaceMembers = (organizationId: string) => {linearMemberAccessStore(client, token, memberConfigScope, organizationId).invalidate();};- const manifestDirty = [PUBLIC_BASE_URL_KEY, WEBHOOK_PATH_KEY, CALLBACK_PATH_KEY].some(- (key) => fieldValues[key] !== savedValues[key],- );const credentialsSaved = fields.filter((field) => !field.optional).every((field) =>configuredFields.has(field.key) || Boolean(feature.config_values?.[field.key]?.trim()),);- const workspaceActionsDisabled = busy || dirty || connecting || loadingInstallations- || disconnectingId !== null;- const savedBaseUrl = feature.config_values?.[PUBLIC_BASE_URL_KEY]?.replace(/\/$/, "");- const manifestUrl = savedBaseUrl- ? linearManifestUrl(- savedBaseUrl,- feature.config_values?.[WEBHOOK_PATH_KEY] || "/linear/webhook",- feature.config_values?.[CALLBACK_PATH_KEY] || "/linear/oauth/callback",- )- : null;-const loadInstallations = useCallback(async (force = false) => {if (!credentialsSaved || dirty) return;setWorkspaceNotice(null);@@ -171,7 +111,7 @@ export function LinearPanel({});}, [client, feature.runtime_status, loadInstallations]);- const disconnectWorkspace = async (installation: LinearInstallationSummary) => {+ const disconnectWorkspace = async (installation: LinearInstallationSummary, onRemoved: () => void) => {setDisconnectingId(installation.organization_id);setWorkspaceNotice(null);setWorkspaceError(null);@@ -187,7 +127,7 @@ export function LinearPanel({forgetWorkspaceMembers(installation.organization_id);workspaceStore.replace(remaining);setWorkspaceNotice(payload.message ?? null);- setDisconnectConfirmId(null);+ onRemoved();setConnectRequestId(0);setConnectionGeneration(value => value + 1);if (remaining.length === 0) {@@ -303,314 +243,30 @@ export function LinearPanel({compact: true,};- return (- <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>- <form className="flex min-w-0 flex-col gap-4" onSubmit={(event) => {- event.preventDefault();- void saveSettings();- }}>- <div className="flex min-h-10 flex-wrap items-center justify-between gap-3 pe-20">- <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />- <h3 className="sr-only">{displayName}</h3>- <span role="status" aria-live="polite" aria-atomic="true"- className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">- {saving ? t("settings.actions.saving", { defaultValue: "Saving" })- : saved ? t("settings.channels.savedSettings", { defaultValue: "Settings saved." }) : ""}- </span>- {feature.runtime_status === "running" ? (- <span role="status" className={cn(- "ms-auto inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[11.5px] font-medium leading-none",- channelValidationStatusClass("connected"),- )}>- <Check className="h-3.5 w-3.5" aria-hidden />- {tx("custom.channelRunning", "Channel running")}- </span>- ) : null}- <button type="button"- className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded px-1 text-[12px] leading-none text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"- aria-expanded={advancedOpen} aria-controls={advancedPanelId}- onClick={() => setAdvancedOpen((current) => !current)}>- {t("settings.channels.advanced", { defaultValue: "Advanced" })}- <ChevronDown className={cn(- "h-3.5 w-3.5 transition-transform motion-reduce:transition-none",- advancedOpen && "rotate-180",- )} aria-hidden />- </button>- </div>- <ChannelRuntimeError message={feature.runtime_error} />- <CredentialForm {...formProps} fields={fields.filter((field) => field.key === PUBLIC_BASE_URL_KEY)} />- <div className="grid gap-y-4">- {fields.filter(field => field.key !== PUBLIC_BASE_URL_KEY).map(field => field.secret ? (- <LinearSecretField key={`${field.key}:${connectionGeneration}`} field={field} configured={configuredFields.has(field.key)}- disabled={busy || dirty || connecting} onSave={saveSecret} />- ) : <CredentialForm key={field.key} {...formProps} fields={[field]} />)}- </div>- <div id={advancedPanelId} hidden={!advancedOpen}>- <CredentialForm {...formProps} fields={advancedFields} />- {installations.some(installation => installation.scopes?.length) ? (- <div className="mt-3 space-y-2 rounded-control bg-muted/45 p-3 text-[12px] text-muted-foreground">- <p className="font-medium">{tx("custom.workspacesTitle", "Authorized workspaces")}</p>- {installations.filter(installation => installation.scopes?.length).map(installation => (- <p key={installation.organization_id} className="break-words">- {installation.organization_name || installation.organization_id}: {installation.scopes?.join(", ")}- </p>- ))}- </div>- ) : null}- <LinearResetConnection fields={editableFields}- disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null- || !(hasSavedSecrets || feature.config_values?.["channels.linear.clientId"] || savedBaseUrl)}- onBusyChange={setResetting} onWorkspacesChange={workspaceStore.replace}- onWorkspaceRemoved={forgetWorkspaceMembers} onFeaturesUpdate={onFeaturesUpdate}- onComplete={() => {- setConnectRequestId(0);- setConnectionGeneration(value => value + 1);- setAdvancedOpen(false);- setWorkspaceNotice(null);- setWorkspaceError(null);- }} />- </div>- {notice ? (- <div className="flex flex-wrap items-center justify-between gap-2 rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5">- <p role="alert">{notice}</p>- <Button type="submit" variant="secondary" size="sm" disabled={busy || connecting}- className="min-h-10 rounded-full text-[12px]">- {tx("custom.retrySave", "Retry")}- </Button>- </div>- ) : null}- </form>- {credentialsSaved || installations.length > 0 ? (- <section className="mt-5 space-y-3" aria-labelledby="linear-workspaces-heading">- <div className="flex flex-wrap items-center justify-between gap-2">- <h4 id="linear-workspaces-heading" className="text-[13px] font-semibold text-foreground">- {tx("custom.workspacesTitle", "Authorized workspaces")}- </h4>- <Button type="button" variant="ghost" size="sm"- disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null}- className="h-8 gap-2 rounded-full text-[12px] text-muted-foreground"- onClick={() => void loadInstallations(true)}>- <RefreshCw className="h-3.5 w-3.5" aria-hidden />- {tx("custom.refreshWorkspaces", "Refresh workspaces")}- </Button>- </div>- <div role="status" aria-live="polite" className="sr-only">- {loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}- </div>- {loadingInstallations && !cachedInstallations ? (- <p className="px-3 py-2.5 text-[12px] text-muted-foreground">- {tx("custom.loadingWorkspaces", "Loading workspaces")}- </p>- ) : null}- {!loadingInstallations && !workspaceError && !inspectionError && cachedInstallations?.length === 0 ? (- <p className="rounded-control bg-muted/45 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground">- {tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}- </p>- ) : null}- <div className="space-y-2">- {installations.map((installation) => {- const name = installation.organization_name || installation.organization_id;- const needsAuthorization = installation.authorization_status === "missing_scopes"- || installation.authorization_status === "refresh_required";- const authorizationWarning = needsAuthorization ? (- <span className="inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground">- <AlertCircle className="h-3 w-3 shrink-0" aria-hidden />- {installation.authorization_status === "missing_scopes"- ? tx("custom.missingScopes", "Reconnect to grant: {{scopes}}", {- scopes: installation.missing_scopes?.join(", ") || "required scopes",- })- : installation.authorization_status === "refresh_required"- ? tx("custom.refreshRequired", "Authorization refresh required")- : tx("custom.authorized", "Authorized")}- </span>- ) : null;- return (- <article key={installation.organization_id} aria-label={name}- className="overflow-hidden rounded-panel border border-border/70 bg-background">- <header className="flex flex-wrap items-center justify-between gap-3 p-4">- <div className="flex min-w-0 flex-1 items-center gap-2.5">- <LinearAvatar name={name} url={logos[installation.organization_id]} workspace />- <div className="min-w-0">- <h5 className="truncate text-[14px] font-semibold text-foreground" title={name}>{name}</h5>- {authorizationWarning ? <div className="mt-1">{authorizationWarning}</div> : null}- </div>- </div>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button type="button" variant="ghost" size="icon"- disabled={workspaceActionsDisabled}- onPointerDown={event => { workspaceActionRef.current = event.currentTarget; }}- onFocus={event => { workspaceActionRef.current = event.currentTarget; }}- aria-label={tx("custom.workspaceActions", "Manage {{name}}", { name })}- title={tx("custom.workspaceActions", "Manage {{name}}", { name })}- className="h-8 w-8 shrink-0 rounded-full text-muted-foreground">- <MoreHorizontal className="h-4 w-4" aria-hidden />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end" onCloseAutoFocus={event => {- if (skipMenuRestoreFocus.current) event.preventDefault();- skipMenuRestoreFocus.current = false;- }}>- <DropdownMenuItem disabled={workspaceActionsDisabled || !credentialsSaved}- onSelect={() => {- skipMenuRestoreFocus.current = true;- setConnectRequestId(id => id + 1);- }}>- <RefreshCw className="h-4 w-4" aria-hidden />- {tx("custom.reauthorize", "Reauthorize")}- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem tone="destructive" disabled={workspaceActionsDisabled}- onSelect={() => {- skipMenuRestoreFocus.current = true;- setWorkspaceError(null);- setDisconnectConfirmId(installation.organization_id);- }}>- <Unplug className="h-4 w-4" aria-hidden />- {tx("custom.disconnect", "Remove workspace")}- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- </header>- <LinearMemberAccess organizationId={installation.organization_id}- configScope={memberConfigScope}- disabled={busy || dirty || connecting || disconnectingId !== null} />- </article>- );- })}- </div>- {installations.length > 0 ? (- <div className="flex items-center gap-1">- <Button type="button" variant="ghost" size="sm"- disabled={workspaceActionsDisabled || !credentialsSaved}- className="h-9 gap-2 rounded-full text-[12px] text-muted-foreground"- onClick={() => setConnectRequestId(id => id + 1)}>- <Plus className="h-3.5 w-3.5" aria-hidden />- {tx("custom.addWorkspace", "Connect workspace")}- </Button>- <SettingsHint description={tx("custom.addWorkspaceHelp", "Uses the current Linear app. To connect another workspace, the app must allow installation in other workspaces; private apps only work in their own workspace. Authorizing an existing workspace updates its connection without creating a duplicate.")}>- <span className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground">- <Info className="h-3.5 w-3.5" aria-hidden />- <span className="sr-only">{tx("custom.addWorkspaceDetails", "About connecting workspaces")}</span>- </span>- </SettingsHint>- </div>- ) : null}- {(workspaceError && !disconnectTarget) || inspectionError ? (- <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError || inspectionError}</p>- ) : null}- {workspaceNotice ? (- <p role="status" className="text-[12px] leading-5 text-muted-foreground">- {workspaceNotice}- </p>- ) : null}- </section>- ) : null}- <LinearConnectFlow key={connectionGeneration} token={token} feature={feature}- connectRequestId={connectRequestId}- connected={feature.runtime_status === "running" && installations.length > 0}- idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={(payload) => {- onFeaturesUpdate(payload);- void workspaceStore.load(true);- }}- onActiveChange={setConnecting}- renderActions={(connectButton) => (- <div className="flex flex-wrap items-center justify-end gap-2 sm:grid sm:grid-cols-[minmax(0,1fr)_auto_auto]">- <div className="me-auto flex min-w-0 max-w-full flex-wrap items-center gap-2">- <Button type="button" variant="outline" size="sm"- className="h-auto min-h-10 whitespace-normal rounded-full px-4 py-2 text-[12px]"- disabled={busy || connecting || !onConfigureMcp}- onClick={async () => {- if (await saveSettings()) onConfigureMcp?.("linear");- }}>- {tx("custom.configureTools", "Configure Linear MCP")}- </Button>- {manifestUrl && !manifestDirty ? (- <Button asChild variant="outline" size="sm"- className="h-auto min-h-10 max-w-full gap-2 whitespace-normal rounded-full px-4 py-2 text-[12px]">- <a href={manifestUrl} target="_blank" rel="noreferrer">- {tx("custom.createApp", "Create Linear app")}- <ExternalLink className="h-3.5 w-3.5 shrink-0" aria-hidden />- </a>- </Button>- ) : (- <Button type="button" variant="outline" size="sm"- disabled={Boolean(fieldValues[PUBLIC_BASE_URL_KEY]?.trim())}- onClick={() => setPublicUrlPromptOpen(true)}- className="h-auto min-h-10 max-w-full whitespace-normal rounded-full px-4 py-2 text-[12px]">- {tx("custom.createApp", "Create Linear app")}- </Button>- )}- </div>- {installations.length === 0 || feature.runtime_status !== "running" || connecting ? (- <fieldset disabled={busy || dirty || !credentialsSaved || loadingInstallations || disconnectingId !== null}- className="min-w-0 sm:col-start-3">- <legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>- {connectButton}- </fieldset>- ) : null}- </div>- )} />- <AlertDialog open={Boolean(disconnectTarget)} onOpenChange={open => {- if (!open && !disconnectingId) {- setDisconnectConfirmId(null);- setWorkspaceError(null);- }- }}>- <AlertDialogContent onEscapeKeyDown={event => {- if (disconnectingId) event.preventDefault();- }} onCloseAutoFocus={event => {- event.preventDefault();- if (workspaceActionRef.current?.isConnected) workspaceActionRef.current.focus();- else document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();- }}>- <AlertDialogHeader>- <AlertDialogTitle>- {tx("custom.disconnectTitle", "Remove {{name}}?", {- name: disconnectTarget?.organization_name || disconnectTarget?.organization_id || "",- })}- </AlertDialogTitle>- <AlertDialogDescription>- {tx("custom.disconnectDescription", "Revoke this workspace's authorization and clear its member access settings in nanobot. Linear issues, comments, and nanobot conversation history will be kept. Other workspaces are not affected. You can authorize this workspace again later.")}- {installations.length === 1 ? <> {tx("custom.disconnectLast", "This is the last connected workspace, so the Linear channel will also be turned off.")}</> : null}- </AlertDialogDescription>- </AlertDialogHeader>- {workspaceError ? <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p> : null}- <AlertDialogFooter>- <AlertDialogCancel disabled={disconnectingId !== null}>- {t("settings.actions.cancel", { defaultValue: "Cancel" })}- </AlertDialogCancel>- <Button type="button" variant="destructive"- disabled={workspaceActionsDisabled || !disconnectTarget}- onClick={() => { if (disconnectTarget) void disconnectWorkspace(disconnectTarget); }}>- {disconnectingId ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}- {disconnectingId- ? tx("custom.disconnecting", "Removing…")- : tx("custom.confirmDisconnect", "Remove workspace")}- </Button>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- <AlertDialog open={publicUrlPromptOpen} onOpenChange={setPublicUrlPromptOpen}>- <AlertDialogContent onCloseAutoFocus={(event) => {- event.preventDefault();- document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();- }}>- <AlertDialogHeader>- <AlertDialogTitle>- {tx("setup.fields.publicBaseUrl.label", "Public HTTPS URL")}- </AlertDialogTitle>- <AlertDialogDescription>- {tx("custom.savePublicUrl", "Enter a public HTTPS URL to create a Linear app.")}- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>- {t("common.close", { defaultValue: "Close" })}- </AlertDialogCancel>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- </aside>- );+ return <LinearPanelView feature={feature} showBrandLogos={showBrandLogos} fields={fields}+ advancedFields={advancedFields} formProps={formProps}+ state={{ busy, dirty, saving, saved, connecting, credentialsSaved, connectionGeneration, notice }}+ workspaces={{ installations: cachedInstallations, logos, loading: loadingInstallations, inspectionError,+ disconnectingId, notice: workspaceNotice, error: workspaceError }}+ onSave={saveSettings} onSaveSecret={saveSecret} onRefreshWorkspaces={loadInstallations}+ onDisconnectWorkspace={disconnectWorkspace} onClearWorkspaceError={() => setWorkspaceError(null)}+ onRequestConnection={() => setConnectRequestId(id => id + 1)} onConfigureMcp={onConfigureMcp}+ renderMemberAccess={(organizationId, disabled) => <LinearMemberAccess organizationId={organizationId}+ configScope={memberConfigScope} disabled={disabled} />}+ renderResetConnection={({ disabled, onComplete }) => <LinearResetConnection fields={editableFields}+ disabled={disabled} onBusyChange={setResetting} onWorkspacesChange={workspaceStore.replace}+ onWorkspaceRemoved={forgetWorkspaceMembers} onFeaturesUpdate={onFeaturesUpdate}+ onComplete={() => {+ setConnectRequestId(0);+ setConnectionGeneration(value => value + 1);+ setWorkspaceNotice(null);+ setWorkspaceError(null);+ onComplete();+ }} />}+ renderConnectFlow={(renderActions) => <LinearConnectFlow key={connectionGeneration} token={token} feature={feature}+ connectRequestId={connectRequestId} connected={feature.runtime_status === "running" && installations.length > 0}+ idleLabel={tx("custom.connect", "Connect Linear")} onFeaturesUpdate={(payload) => {+ onFeaturesUpdate(payload);+ void workspaceStore.load(true);+ }} onActiveChange={setConnecting} renderActions={renderActions} />} />;}diff --git a/nanobot/channels/linear/webui/LinearPanelView.tsx b/nanobot/channels/linear/webui/LinearPanelView.tsxnew file mode 100644index 000000000..06d897f7e--- /dev/null+++ b/nanobot/channels/linear/webui/LinearPanelView.tsx@@ -0,0 +1,391 @@+import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";+import { AlertCircle, Check, ChevronDown, ExternalLink, Info, Loader2, MoreHorizontal, Plus, RefreshCw, Unplug } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import type { ChannelPluginPanelProps } from "@/channel-plugins/types";+import { CredentialForm, channelFieldInputId, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";+import { CHANNEL_SETUP_PANEL_CLASS_NAME, ChannelLogo, ChannelRuntimeError, localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";+import type { ChannelConfigField } from "@/channel-plugins/catalog";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { channelValidationStatusClass } from "@/components/settings/channels/ChannelValidationProgress";+import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { cn } from "@/lib/utils";++import { LinearAvatar } from "./LinearAvatar";+import { LinearSecretField } from "./LinearSecretField";+import type { LinearInstallationSummary } from "./types";+import { linearManifestUrl } from "./manifest";++const PUBLIC_BASE_URL_KEY = "channels.linear.publicBaseUrl";+const WEBHOOK_PATH_KEY = "channels.linear.webhookPath";+const CALLBACK_PATH_KEY = "channels.linear.oauthCallbackPath";++export interface LinearPanelState {+ busy: boolean;+ dirty: boolean;+ saving: boolean;+ saved: boolean;+ connecting: boolean;+ credentialsSaved: boolean;+ connectionGeneration: number;+ notice: string | null;+}++export interface LinearPanelWorkspaces {+ installations: LinearInstallationSummary[] | null;+ logos: Record<string, string | null>;+ loading: boolean;+ inspectionError: string | null;+ disconnectingId: string | null;+ notice: string | null;+ error: string | null;+}++export interface LinearPanelViewProps {+ feature: ChannelPluginPanelProps["feature"];+ showBrandLogos: boolean;+ fields: ChannelConfigField[];+ advancedFields: ChannelConfigField[];+ formProps: Omit<ComponentProps<typeof CredentialForm>, "fields">;+ state: LinearPanelState;+ workspaces: LinearPanelWorkspaces;+ onSave: () => Promise<boolean>;+ onSaveSecret: (key: string, value: string) => Promise<void>;+ onRefreshWorkspaces: (force?: boolean) => Promise<void>;+ onDisconnectWorkspace: (installation: LinearInstallationSummary, onRemoved: () => void) => Promise<void>;+ onClearWorkspaceError: () => void;+ onRequestConnection: () => void;+ onConfigureMcp?: ChannelPluginPanelProps["onConfigureMcp"];+ renderMemberAccess: (organizationId: string, disabled: boolean) => ReactNode;+ renderResetConnection: (props: { disabled: boolean; onComplete: () => void }) => ReactNode;+ renderConnectFlow: (renderActions: (connectButton: ReactNode) => ReactNode) => ReactNode;+}++export function LinearPanelView({ feature, showBrandLogos, fields, advancedFields, formProps, state, workspaces,+ onSave: saveSettings, onSaveSecret: saveSecret, onRefreshWorkspaces: loadInstallations,+ onDisconnectWorkspace: disconnectWorkspace, onClearWorkspaceError, onRequestConnection, onConfigureMcp,+ renderMemberAccess, renderResetConnection, renderConnectFlow }: LinearPanelViewProps) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const displayName = localizedChannelDisplayName(feature, t);+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const [publicUrlPromptOpen, setPublicUrlPromptOpen] = useState(false);+ const [disconnectConfirmId, setDisconnectConfirmId] = useState<string | null>(null);+ const workspaceActionRef = useRef<HTMLButtonElement | null>(null);+ const skipMenuRestoreFocus = useRef(false);+ const advancedPanelId = useId();+ const { busy, dirty, saving, saved, connecting, credentialsSaved, connectionGeneration, notice } = state;+ const { installations: cachedInstallations, logos, loading: loadingInstallations, inspectionError,+ disconnectingId, notice: workspaceNotice, error: workspaceError } = workspaces;+ const installations = cachedInstallations ?? [];+ const disconnectTarget = installations.find(item => item.organization_id === disconnectConfirmId);+ const configuredFields = formProps.configuredFields ?? new Set<string>();+ const fieldValues = formProps.values;+ const hasSavedSecrets = [...fields, ...advancedFields].some(field => field.secret && configuredFields.has(field.key));+ const workspaceActionsDisabled = busy || dirty || connecting || loadingInstallations || disconnectingId !== null;+ const savedBaseUrl = feature.config_values?.[PUBLIC_BASE_URL_KEY]?.replace(/\/$/, "");+ const manifestUrl = savedBaseUrl ? linearManifestUrl(savedBaseUrl,+ feature.config_values?.[WEBHOOK_PATH_KEY] || "/linear/webhook",+ feature.config_values?.[CALLBACK_PATH_KEY] || "/linear/oauth/callback") : null;+ const savedValues = defaultChannelFieldValues([...fields, ...advancedFields], feature.config_values);+ const manifestDirty = [PUBLIC_BASE_URL_KEY, WEBHOOK_PATH_KEY, CALLBACK_PATH_KEY].some(+ key => fieldValues[key] !== savedValues[key],+ );+ return (+ <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>+ <form className="flex min-w-0 flex-col gap-4" onSubmit={(event) => {+ event.preventDefault();+ void saveSettings();+ }}>+ <div className="flex min-h-10 flex-wrap items-center justify-between gap-3 pe-20">+ <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />+ <h3 className="sr-only">{displayName}</h3>+ <span role="status" aria-live="polite" aria-atomic="true"+ className="min-w-0 flex-1 truncate text-[11px] text-muted-foreground">+ {saving ? t("settings.actions.saving", { defaultValue: "Saving" })+ : saved ? t("settings.channels.savedSettings", { defaultValue: "Settings saved." }) : ""}+ </span>+ {feature.runtime_status === "running" ? (+ <span role="status" className={cn(+ "ms-auto inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full px-2.5 text-[11.5px] font-medium leading-none",+ channelValidationStatusClass("connected"),+ )}>+ <Check className="h-3.5 w-3.5" aria-hidden />+ {tx("custom.channelRunning", "Channel running")}+ </span>+ ) : null}+ <button type="button"+ className="inline-flex h-8 shrink-0 items-center gap-1.5 rounded px-1 text-[12px] leading-none text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-offset-2"+ aria-expanded={advancedOpen} aria-controls={advancedPanelId}+ onClick={() => setAdvancedOpen((current) => !current)}>+ {t("settings.channels.advanced", { defaultValue: "Advanced" })}+ <ChevronDown className={cn(+ "h-3.5 w-3.5 transition-transform motion-reduce:transition-none",+ advancedOpen && "rotate-180",+ )} aria-hidden />+ </button>+ </div>+ <ChannelRuntimeError message={feature.runtime_error} />+ <CredentialForm {...formProps} fields={fields.filter((field) => field.key === PUBLIC_BASE_URL_KEY)} />+ <div className="grid gap-y-4">+ {fields.filter(field => field.key !== PUBLIC_BASE_URL_KEY).map(field => field.secret ? (+ <LinearSecretField key={`${field.key}:${connectionGeneration}`} field={field} configured={configuredFields.has(field.key)}+ disabled={busy || dirty || connecting} onSave={saveSecret} />+ ) : <CredentialForm key={field.key} {...formProps} fields={[field]} />)}+ </div>+ <div id={advancedPanelId} hidden={!advancedOpen}>+ <CredentialForm {...formProps} fields={advancedFields} />+ {installations.some(installation => installation.scopes?.length) ? (+ <div className="mt-3 space-y-2 rounded-control bg-muted/45 p-3 text-[12px] text-muted-foreground">+ <p className="font-medium">{tx("custom.workspacesTitle", "Authorized workspaces")}</p>+ {installations.filter(installation => installation.scopes?.length).map(installation => (+ <p key={installation.organization_id} className="break-words">+ {installation.organization_name || installation.organization_id}: {installation.scopes?.join(", ")}+ </p>+ ))}+ </div>+ ) : null}+ {renderResetConnection({+ disabled: busy || dirty || connecting || loadingInstallations || disconnectingId !== null+ || !(hasSavedSecrets || feature.config_values?.["channels.linear.clientId"] || savedBaseUrl),+ onComplete: () => setAdvancedOpen(false),+ })}+ </div>+ {notice ? (+ <div className="flex flex-wrap items-center justify-between gap-2 rounded-control bg-muted/55 px-3 py-2.5 text-[12px] leading-5">+ <p role="alert">{notice}</p>+ <Button type="submit" variant="secondary" size="sm" disabled={busy || connecting}+ className="min-h-10 rounded-full text-[12px]">+ {tx("custom.retrySave", "Retry")}+ </Button>+ </div>+ ) : null}+ </form>+ {credentialsSaved || installations.length > 0 ? (+ <section className="mt-5 space-y-3" aria-labelledby="linear-workspaces-heading">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h4 id="linear-workspaces-heading" className="text-[13px] font-semibold text-foreground">+ {tx("custom.workspacesTitle", "Authorized workspaces")}+ </h4>+ <Button type="button" variant="ghost" size="sm"+ disabled={busy || dirty || connecting || loadingInstallations || disconnectingId !== null}+ className="h-8 gap-2 rounded-full text-[12px] text-muted-foreground"+ onClick={() => void loadInstallations(true)}>+ <RefreshCw className="h-3.5 w-3.5" aria-hidden />+ {tx("custom.refreshWorkspaces", "Refresh workspaces")}+ </Button>+ </div>+ <div role="status" aria-live="polite" className="sr-only">+ {loadingInstallations ? tx("custom.loadingWorkspaces", "Loading workspaces") : ""}+ </div>+ {loadingInstallations && !cachedInstallations ? (+ <p className="px-3 py-2.5 text-[12px] text-muted-foreground">+ {tx("custom.loadingWorkspaces", "Loading workspaces")}+ </p>+ ) : null}+ {!loadingInstallations && !workspaceError && !inspectionError && cachedInstallations?.length === 0 ? (+ <p className="rounded-control bg-muted/45 px-3 py-2.5 text-[12px] leading-5 text-muted-foreground">+ {tx("custom.noWorkspaces", "No workspaces are authorized. Connect a workspace to receive Linear agent requests.")}+ </p>+ ) : null}+ <div className="space-y-2">+ {installations.map((installation) => {+ const name = installation.organization_name || installation.organization_id;+ const needsAuthorization = installation.authorization_status === "missing_scopes"+ || installation.authorization_status === "refresh_required";+ const authorizationWarning = needsAuthorization ? (+ <span className="inline-flex items-center gap-1.5 text-[11px] leading-4 text-muted-foreground">+ <AlertCircle className="h-3 w-3 shrink-0" aria-hidden />+ {installation.authorization_status === "missing_scopes"+ ? tx("custom.missingScopes", "Reconnect to grant: {{scopes}}", {+ scopes: installation.missing_scopes?.join(", ") || "required scopes",+ })+ : installation.authorization_status === "refresh_required"+ ? tx("custom.refreshRequired", "Authorization refresh required")+ : tx("custom.authorized", "Authorized")}+ </span>+ ) : null;+ return (+ <article key={installation.organization_id} aria-label={name}+ className="overflow-hidden rounded-panel border border-border/70 bg-background">+ <header className="flex flex-wrap items-center justify-between gap-3 p-4">+ <div className="flex min-w-0 flex-1 items-center gap-2.5">+ <LinearAvatar name={name} url={logos[installation.organization_id]} workspace />+ <div className="min-w-0">+ <h5 className="truncate text-[14px] font-semibold text-foreground" title={name}>{name}</h5>+ {authorizationWarning ? <div className="mt-1">{authorizationWarning}</div> : null}+ </div>+ </div>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button type="button" variant="ghost" size="icon"+ disabled={workspaceActionsDisabled}+ onPointerDown={event => { workspaceActionRef.current = event.currentTarget; }}+ onFocus={event => { workspaceActionRef.current = event.currentTarget; }}+ aria-label={tx("custom.workspaceActions", "Manage {{name}}", { name })}+ title={tx("custom.workspaceActions", "Manage {{name}}", { name })}+ className="h-8 w-8 shrink-0 rounded-full text-muted-foreground">+ <MoreHorizontal className="h-4 w-4" aria-hidden />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" onCloseAutoFocus={event => {+ if (skipMenuRestoreFocus.current) event.preventDefault();+ skipMenuRestoreFocus.current = false;+ }}>+ <DropdownMenuItem disabled={workspaceActionsDisabled || !credentialsSaved}+ onSelect={() => {+ skipMenuRestoreFocus.current = true;+ onRequestConnection();+ }}>+ <RefreshCw className="h-4 w-4" aria-hidden />+ {tx("custom.reauthorize", "Reauthorize")}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem tone="destructive" disabled={workspaceActionsDisabled}+ onSelect={() => {+ skipMenuRestoreFocus.current = true;+ onClearWorkspaceError();+ setDisconnectConfirmId(installation.organization_id);+ }}>+ <Unplug className="h-4 w-4" aria-hidden />+ {tx("custom.disconnect", "Remove workspace")}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </header>+ {renderMemberAccess(installation.organization_id,+ busy || dirty || connecting || disconnectingId !== null)}+ </article>+ );+ })}+ </div>+ {installations.length > 0 ? (+ <div className="flex items-center gap-1">+ <Button type="button" variant="ghost" size="sm"+ disabled={workspaceActionsDisabled || !credentialsSaved}+ className="h-9 gap-2 rounded-full text-[12px] text-muted-foreground"+ onClick={() => onRequestConnection()}>+ <Plus className="h-3.5 w-3.5" aria-hidden />+ {tx("custom.addWorkspace", "Connect workspace")}+ </Button>+ <SettingsHint description={tx("custom.addWorkspaceHelp", "Uses the current Linear app. To connect another workspace, the app must allow installation in other workspaces; private apps only work in their own workspace. Authorizing an existing workspace updates its connection without creating a duplicate.")}>+ <span className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground">+ <Info className="h-3.5 w-3.5" aria-hidden />+ <span className="sr-only">{tx("custom.addWorkspaceDetails", "About connecting workspaces")}</span>+ </span>+ </SettingsHint>+ </div>+ ) : null}+ {(workspaceError && !disconnectTarget) || inspectionError ? (+ <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError || inspectionError}</p>+ ) : null}+ {workspaceNotice ? (+ <p role="status" className="text-[12px] leading-5 text-muted-foreground">+ {workspaceNotice}+ </p>+ ) : null}+ </section>+ ) : null}+ {renderConnectFlow((connectButton) => (+ <div className="flex flex-wrap items-center justify-end gap-2 sm:grid sm:grid-cols-[minmax(0,1fr)_auto_auto]">+ <div className="me-auto flex min-w-0 max-w-full flex-wrap items-center gap-2">+ <Button type="button" variant="outline" size="sm"+ className="h-auto min-h-10 whitespace-normal rounded-full px-4 py-2 text-[12px]"+ disabled={busy || connecting || !onConfigureMcp}+ onClick={async () => {+ if (await saveSettings()) onConfigureMcp?.("linear");+ }}>+ {tx("custom.configureTools", "Configure Linear MCP")}+ </Button>+ {manifestUrl && !manifestDirty ? (+ <Button asChild variant="outline" size="sm"+ className="h-auto min-h-10 max-w-full gap-2 whitespace-normal rounded-full px-4 py-2 text-[12px]">+ <a href={manifestUrl} target="_blank" rel="noreferrer">+ {tx("custom.createApp", "Create Linear app")}+ <ExternalLink className="h-3.5 w-3.5 shrink-0" aria-hidden />+ </a>+ </Button>+ ) : (+ <Button type="button" variant="outline" size="sm"+ disabled={Boolean(fieldValues[PUBLIC_BASE_URL_KEY]?.trim())}+ onClick={() => setPublicUrlPromptOpen(true)}+ className="h-auto min-h-10 max-w-full whitespace-normal rounded-full px-4 py-2 text-[12px]">+ {tx("custom.createApp", "Create Linear app")}+ </Button>+ )}+ </div>+ {installations.length === 0 || feature.runtime_status !== "running" || connecting ? (+ <fieldset disabled={busy || dirty || !credentialsSaved || loadingInstallations || disconnectingId !== null}+ className="min-w-0 sm:col-start-3">+ <legend className="sr-only">{tx("custom.authorizeTitle", "Authorize in Linear")}</legend>+ {connectButton}+ </fieldset>+ ) : null}+ </div>+ ))}+ <AlertDialog open={Boolean(disconnectTarget)} onOpenChange={open => {+ if (!open && !disconnectingId) {+ setDisconnectConfirmId(null);+ onClearWorkspaceError();+ }+ }}>+ <AlertDialogContent onEscapeKeyDown={event => {+ if (disconnectingId) event.preventDefault();+ }} onCloseAutoFocus={event => {+ event.preventDefault();+ if (workspaceActionRef.current?.isConnected) workspaceActionRef.current.focus();+ else document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();+ }}>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {tx("custom.disconnectTitle", "Remove {{name}}?", {+ name: disconnectTarget?.organization_name || disconnectTarget?.organization_id || "",+ })}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {tx("custom.disconnectDescription", "Revoke this workspace's authorization and clear its member access settings in nanobot. Linear issues, comments, and nanobot conversation history will be kept. Other workspaces are not affected. You can authorize this workspace again later.")}+ {installations.length === 1 ? <> {tx("custom.disconnectLast", "This is the last connected workspace, so the Linear channel will also be turned off.")}</> : null}+ </AlertDialogDescription>+ </AlertDialogHeader>+ {workspaceError ? <p role="alert" className="text-[12px] leading-5 text-destructive">{workspaceError}</p> : null}+ <AlertDialogFooter>+ <AlertDialogCancel disabled={disconnectingId !== null}>+ {t("settings.actions.cancel", { defaultValue: "Cancel" })}+ </AlertDialogCancel>+ <Button type="button" variant="destructive"+ disabled={workspaceActionsDisabled || !disconnectTarget}+ onClick={() => { if (disconnectTarget) void disconnectWorkspace(disconnectTarget, () => setDisconnectConfirmId(null)); }}>+ {disconnectingId ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}+ {disconnectingId+ ? tx("custom.disconnecting", "Removing…")+ : tx("custom.confirmDisconnect", "Remove workspace")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ <AlertDialog open={publicUrlPromptOpen} onOpenChange={setPublicUrlPromptOpen}>+ <AlertDialogContent onCloseAutoFocus={(event) => {+ event.preventDefault();+ document.getElementById(channelFieldInputId(PUBLIC_BASE_URL_KEY))?.focus();+ }}>+ <AlertDialogHeader>+ <AlertDialogTitle>+ {tx("setup.fields.publicBaseUrl.label", "Public HTTPS URL")}+ </AlertDialogTitle>+ <AlertDialogDescription>+ {tx("custom.savePublicUrl", "Enter a public HTTPS URL to create a Linear app.")}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>+ {t("common.close", { defaultValue: "Close" })}+ </AlertDialogCancel>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </aside>+ );+}diff --git a/nanobot/channels/linear/webui/LinearResetConnection.tsx b/nanobot/channels/linear/webui/LinearResetConnection.tsxindex ebc4e3635..e5feea538 100644--- a/nanobot/channels/linear/webui/LinearResetConnection.tsx+++ b/nanobot/channels/linear/webui/LinearResetConnection.tsx@@ -1,21 +1,15 @@-import { useRef, useState } from "react";-import { Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";import { channelTranslator } from "@/channel-plugins/i18n";import type { ChannelConfigField } from "@/channel-plugins/catalog";-import { channelFieldInputId, defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";-import { Button } from "@/components/ui/button";-import {- AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,- AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,-} from "@/components/ui/alert-dialog";+import { defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";import { configureChannel, disableNanobotFeature } from "@/lib/api";import type { NanobotFeaturesPayload } from "@/lib/types";import { useClient } from "@/providers/ClientProvider";import { manageLinearWorkspace } from "./api";import type { LinearInstallationSummary } from "./types";+import { LinearResetConnectionView } from "./LinearResetConnectionView";/** Keep credentials until every workspace has been revoked and the channel has stopped. */export function LinearResetConnection({@@ -32,18 +26,8 @@ export function LinearResetConnection({const { client } = useClient();const { t } = useTranslation();const tx = channelTranslator(t, "linear");- const [open, setOpen] = useState(false);- const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);- const inFlight = useRef(false);- const triggerRef = useRef<HTMLButtonElement>(null);-const reset = async () => {- if (inFlight.current) return;- inFlight.current = true;- setBusy(true);onBusyChange(true);- setError(null);try {// Inspect even when the channel is stopped or the display cache is empty/stale.const current = await manageLinearWorkspace(client, { operation: "inspect" });@@ -79,59 +63,10 @@ export function LinearResetConnection({if (!result.saved) throw new Error(tx("custom.resetSaveFailed", "Could not clear the app settings. Please retry."));if (result.nanobot_features) onFeaturesUpdate(result.nanobot_features);onComplete?.();- setOpen(false);- } catch (err) {- setError(err instanceof Error ? err.message : String(err));} finally {- inFlight.current = false;- setBusy(false);onBusyChange(false);}};- return <AlertDialog open={open} onOpenChange={value => {- if (inFlight.current) return;- setOpen(value);- setError(null);- }}>- <div className="mt-4 border-t border-border/60 pt-3">- <Button ref={triggerRef} type="button" variant="ghost" size="sm" disabled={disabled || busy}- onClick={() => { setError(null); setOpen(true); }}- className="h-8 rounded-full text-[12px] text-muted-foreground hover:text-destructive">- {tx("custom.resetConnection", "Reset Linear connection")}- </Button>- </div>- <AlertDialogContent className="max-w-md gap-5" onEscapeKeyDown={event => { if (inFlight.current) event.preventDefault(); }}- onCloseAutoFocus={event => {- event.preventDefault();- if (triggerRef.current && !triggerRef.current.disabled) triggerRef.current.focus();- else document.getElementById(channelFieldInputId("channels.linear.publicBaseUrl"))?.focus();- }}>- <AlertDialogHeader className="space-y-3 text-left">- <AlertDialogTitle>{tx("custom.resetTitle", "Reset Linear?")}</AlertDialogTitle>- <AlertDialogDescription asChild>- <div className="space-y-4 text-sm leading-6">- <p>{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}</p>- <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-3 rounded-xl bg-muted/40 p-4 text-[13px] leading-5">- <dt className="font-medium text-foreground">{tx("custom.resetClears", "Clears")}</dt>- <dd>{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}</dd>- <dt className="font-medium text-foreground">{tx("custom.resetKeeps", "Keeps")}</dt>- <dd>{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}</dd>- </dl>- </div>- </AlertDialogDescription>- </AlertDialogHeader>- {error ? <div role="alert" className="space-y-1 text-[12px] leading-5 text-destructive">- <p>{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}</p>- <p>{error}</p>- </div> : null}- <AlertDialogFooter>- <AlertDialogCancel className="h-9 min-w-20 rounded-full text-[13px]" disabled={busy}>{t("settings.actions.cancel", { defaultValue: "Cancel" })}</AlertDialogCancel>- <Button type="button" variant="destructive" size="sm" className="min-w-20 rounded-full px-4 text-[13px]" disabled={busy} onClick={() => void reset()}>- {busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}- {busy ? tx("custom.resetting", "Resetting…") : tx("custom.resetConfirm", "Reset")}- </Button>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>;+ return <LinearResetConnectionView disabled={disabled} onReset={reset} />;}diff --git a/nanobot/channels/linear/webui/LinearResetConnectionView.tsx b/nanobot/channels/linear/webui/LinearResetConnectionView.tsxnew file mode 100644index 000000000..4f972b7f3--- /dev/null+++ b/nanobot/channels/linear/webui/LinearResetConnectionView.tsx@@ -0,0 +1,87 @@+import { useRef, useState } from "react";+import { Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { channelFieldInputId } from "@/components/settings/channels/CredentialForm";+import { Button } from "@/components/ui/button";+import {+ AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription,+ AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,+} from "@/components/ui/alert-dialog";+++export function LinearResetConnectionView({ disabled, onReset }: {+ disabled: boolean;+ onReset: () => Promise<void>;+}) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "linear");+ const [open, setOpen] = useState(false);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const inFlight = useRef(false);+ const triggerRef = useRef<HTMLButtonElement>(null);++ const reset = async () => {+ if (inFlight.current) return;+ inFlight.current = true;+ setBusy(true);+ setError(null);+ try {+ await onReset();+ setOpen(false);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ inFlight.current = false;+ setBusy(false);+ }+ };++ return <AlertDialog open={open} onOpenChange={value => {+ if (inFlight.current) return;+ setOpen(value);+ setError(null);+ }}>+ <div className="mt-4 border-t border-border/60 pt-3">+ <Button ref={triggerRef} type="button" variant="ghost" size="sm" disabled={disabled || busy}+ onClick={() => { setError(null); setOpen(true); }}+ className="h-8 rounded-full text-[12px] text-muted-foreground hover:text-destructive">+ {tx("custom.resetConnection", "Reset Linear connection")}+ </Button>+ </div>+ <AlertDialogContent className="max-w-md gap-5" onEscapeKeyDown={event => { if (inFlight.current) event.preventDefault(); }}+ onCloseAutoFocus={event => {+ event.preventDefault();+ if (triggerRef.current && !triggerRef.current.disabled) triggerRef.current.focus();+ else document.getElementById(channelFieldInputId("channels.linear.publicBaseUrl"))?.focus();+ }}>+ <AlertDialogHeader className="space-y-3 text-left">+ <AlertDialogTitle>{tx("custom.resetTitle", "Reset Linear?")}</AlertDialogTitle>+ <AlertDialogDescription asChild>+ <div className="space-y-4 text-sm leading-6">+ <p>{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}</p>+ <dl className="grid grid-cols-[auto_1fr] gap-x-4 gap-y-3 rounded-xl bg-muted/40 p-4 text-[13px] leading-5">+ <dt className="font-medium text-foreground">{tx("custom.resetClears", "Clears")}</dt>+ <dd>{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}</dd>+ <dt className="font-medium text-foreground">{tx("custom.resetKeeps", "Keeps")}</dt>+ <dd>{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}</dd>+ </dl>+ </div>+ </AlertDialogDescription>+ </AlertDialogHeader>+ {error ? <div role="alert" className="space-y-1 text-[12px] leading-5 text-destructive">+ <p>{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}</p>+ <p>{error}</p>+ </div> : null}+ <AlertDialogFooter>+ <AlertDialogCancel className="h-9 min-w-20 rounded-full text-[13px]" disabled={busy}>{t("settings.actions.cancel", { defaultValue: "Cancel" })}</AlertDialogCancel>+ <Button type="button" variant="destructive" size="sm" className="min-w-20 rounded-full px-4 text-[13px]" disabled={busy} onClick={() => void reset()}>+ {busy ? <Loader2 className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden /> : null}+ {busy ? tx("custom.resetting", "Resetting…") : tx("custom.resetConfirm", "Reset")}+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>;+}diff --git a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsxindex 523465b6b..a87286018 100644--- a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx+++ b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx@@ -1,70 +1,12 @@-import { useState } from "react";import { useTranslation } from "react-i18next";-import {- channelTranslator,- type ChannelTranslator,-} from "@/channel-plugins/i18n";import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";-import {- ChannelQrConnectFlow,- type ChannelQrConnectPendingContext,-} from "@/components/settings/channels/ChannelQrConnectFlow";-import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import type { ChannelConnectPayload } from "@/lib/types";+import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";-type WeixinVerificationPayload = ChannelConnectPayload & {- challenge: "verify_code";- verification_failed?: boolean;-};+import { WeixinConnectFlowView, weixinConnectLabels } from "./WeixinConnectFlowView";+import { isVerificationChallenge, WEIXIN_AUTH_EXPIRED_MESSAGE } from "./presentation";-export const WEIXIN_AUTH_EXPIRED_MESSAGE =- "WeChat login expired. Scan again to reconnect.";--function isVerificationChallenge(- payload: ChannelConnectPayload,-): payload is WeixinVerificationPayload {- return (- "challenge" in payload- && payload.challenge === "verify_code"- && (- !("verification_failed" in payload)- || typeof payload.verification_failed === "boolean"- )- );-}--function weixinConnectMessage(- payload: ChannelConnectPayload,- tx: ChannelTranslator,-): string {- if (payload.status === "succeeded") {- return tx("custom.connected", "WeChat is connected.");- }- if (payload.status === "expired") {- return tx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE);- }- if (payload.status === "failed") {- return payload.message- ?? tx("custom.failed", "Unable to connect WeChat. Try again.");- }- if (payload.status === "cancelled") {- return tx("custom.stopped", "WeChat login stopped.");- }- if (isVerificationChallenge(payload)) {- return payload.verification_failed- ? tx(- "custom.verifyMismatch",- "That code did not match. Enter the new number shown in WeChat.",- )- : tx(- "custom.verifyDescription",- "Enter the number shown in WeChat to continue.",- );- }- return tx("custom.waiting", "Waiting for WeChat scan...");-}+export { WEIXIN_AUTH_EXPIRED_MESSAGE } from "./presentation";export function WeixinConnectFlow({token,@@ -75,8 +17,6 @@ export function WeixinConnectFlow({onFeaturesUpdate,}: ChannelPluginConnectFlowProps & { authRecoveryActive?: boolean }) {const { t } = useTranslation();- const tx = channelTranslator(t, "weixin");- const [verificationCode, setVerificationCode] = useState("");const authExpired = authRecoveryActive|| feature.runtime_error === WEIXIN_AUTH_EXPIRED_MESSAGE;const scanAgainLabel = t("settings.channels.scanAgain", {@@ -85,55 +25,6 @@ export function WeixinConnectFlow({if (feature.configured && !authExpired) return null;- const renderVerification = ({- connect,- busy,- poll,- }: ChannelQrConnectPendingContext) => {- if (!isVerificationChallenge(connect)) return null;- return (- <form- className="mt-3 space-y-2"- onSubmit={(event) => {- event.preventDefault();- const code = verificationCode.trim();- if (!code) return;- void poll({ verify_code: code }).then((payload) => {- if (payload && !isVerificationChallenge(payload)) {- setVerificationCode("");- }- });- }}- >- <div className="text-[12px] font-semibold text-foreground">- {tx("custom.verifyTitle", "Verification required")}- </div>- <p className="text-[12px] leading-5 text-muted-foreground">- {weixinConnectMessage(connect, tx)}- </p>- <div className="flex gap-2">- <Input- value={verificationCode}- onChange={(event) => setVerificationCode(event.target.value)}- inputMode="numeric"- autoComplete="one-time-code"- placeholder={tx("custom.verifyPlaceholder", "Code")}- className="h-8 max-w-40"- aria-invalid={connect.verification_failed || undefined}- />- <Button- type="submit"- size="sm"- className="h-8 rounded-full px-3 text-[12px] font-semibold"- disabled={busy || !verificationCode.trim()}- >- {tx("custom.verifySubmit", "Verify")}- </Button>- </div>- </form>- );- };-return (<ChannelQrConnectFlowtoken={token}@@ -147,19 +38,8 @@ export function WeixinConnectFlow({onFeaturesUpdate={onFeaturesUpdate}pausePolling={isVerificationChallenge}suppressSucceeded={feature.runtime_status === "failed"}- renderPending={renderVerification}- resolveMessage={(payload) => weixinConnectMessage(payload, tx)}- labels={{- qrAlt: tx("custom.qrAlt", "WeChat login QR code"),- scanTitle: tx("custom.scanTitle", "Scan with WeChat"),- scanDescription: "",- waiting: tx("custom.waiting", "Waiting for WeChat scan..."),- connected: tx("custom.connected", "WeChat is connected."),- stopped: tx("custom.stopped", "WeChat login stopped."),- connecting: tx("custom.connecting", "Connecting..."),- scanAgain: scanAgainLabel,- connect: t("settings.channels.connect", { defaultValue: "Connect" }),- }}+ labels={weixinConnectLabels(t)}+ renderView={(props) => <WeixinConnectFlowView {...props} />}/>);}diff --git a/nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx b/nanobot/channels/weixin/webui/WeixinConnectFlowView.tsxnew file mode 100644index 000000000..173db22dd--- /dev/null+++ b/nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx@@ -0,0 +1,132 @@+import { useId, useState } from "react";+import { useTranslation } from "react-i18next";++import { channelTranslator, type ChannelTranslator } from "@/channel-plugins/i18n";+import {+ ChannelQrConnectFlowView,+ type ChannelQrConnectFlowViewProps,+ type ChannelQrConnectLabels,+ type ChannelQrConnectPendingContext,+} from "@/components/settings/channels/ChannelQrConnectFlowView";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import type { ChannelConnectPayload } from "@/lib/types";++import { isVerificationChallenge, WEIXIN_AUTH_EXPIRED_MESSAGE } from "./presentation";++function weixinConnectMessage(+ payload: ChannelConnectPayload,+ tx: ChannelTranslator,+): string {+ if (payload.status === "succeeded") {+ return tx("custom.connected", "WeChat is connected.");+ }+ if (payload.status === "expired") {+ return tx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE);+ }+ if (payload.status === "failed") {+ return payload.message+ ?? tx("custom.failed", "Unable to connect WeChat. Try again.");+ }+ if (payload.status === "cancelled") {+ return tx("custom.stopped", "WeChat login stopped.");+ }+ if (isVerificationChallenge(payload)) {+ return payload.verification_failed+ ? tx(+ "custom.verifyMismatch",+ "That code did not match. Enter the new number shown in WeChat.",+ )+ : tx(+ "custom.verifyDescription",+ "Enter the number shown in WeChat to continue.",+ );+ }+ return tx("custom.waiting", "Waiting for WeChat scan...");+}++export function weixinConnectLabels(t: Parameters<typeof channelTranslator>[0]): ChannelQrConnectLabels {+ const tx = channelTranslator(t, "weixin");+ return {+ qrAlt: tx("custom.qrAlt", "WeChat login QR code"),+ scanTitle: tx("custom.scanTitle", "Scan with WeChat"),+ scanDescription: "",+ waiting: tx("custom.waiting", "Waiting for WeChat scan..."),+ connected: tx("custom.connected", "WeChat is connected."),+ stopped: tx("custom.stopped", "WeChat login stopped."),+ connecting: tx("custom.connecting", "Connecting..."),+ scanAgain: t("settings.channels.scanAgain", { defaultValue: "Scan again" }),+ connect: t("settings.channels.connect", { defaultValue: "Connect" }),+ };+}++export type WeixinConnectFlowViewProps = Omit<+ ChannelQrConnectFlowViewProps, "labels" | "renderPending" | "resolveMessage"+>;++export function WeixinConnectFlowView(props: WeixinConnectFlowViewProps) {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "weixin");+ const [verificationCode, setVerificationCode] = useState("");+ const verificationTitleId = useId();+ const verificationMessageId = useId();++ const renderVerification = ({+ connect,+ busy,+ poll,+ }: ChannelQrConnectPendingContext) => {+ if (!isVerificationChallenge(connect)) return null;+ return (+ <form+ className="mt-3 space-y-2"+ aria-labelledby={verificationTitleId}+ onSubmit={(event) => {+ event.preventDefault();+ const code = verificationCode.trim();+ if (!code) return;+ void poll({ verify_code: code }).then((payload) => {+ if (payload && !isVerificationChallenge(payload)) {+ setVerificationCode("");+ }+ });+ }}+ >+ <div id={verificationTitleId} className="text-[12px] font-semibold text-foreground">+ {tx("custom.verifyTitle", "Verification required")}+ </div>+ <p id={verificationMessageId} role={connect.verification_failed ? "alert" : undefined} className="text-[12px] leading-5 text-muted-foreground">+ {weixinConnectMessage(connect, tx)}+ </p>+ <div className="flex gap-2">+ <Input+ value={verificationCode}+ onChange={(event) => setVerificationCode(event.target.value)}+ inputMode="numeric"+ autoComplete="one-time-code"+ placeholder={tx("custom.verifyPlaceholder", "Code")}+ aria-label={tx("custom.verifyPlaceholder", "Code")}+ aria-describedby={verificationMessageId}+ className="h-8 max-w-40"+ aria-invalid={connect.verification_failed || undefined}+ />+ <Button+ type="submit"+ size="sm"+ className="h-8 rounded-full px-3 text-[12px] font-semibold"+ disabled={busy || !verificationCode.trim()}+ >+ {tx("custom.verifySubmit", "Verify")}+ </Button>+ </div>+ </form>+ );+ };++ return <ChannelQrConnectFlowView+ {...props}+ labels={weixinConnectLabels(t)}+ renderPending={renderVerification}+ resolveMessage={(payload) => weixinConnectMessage(payload, tx)}+ />;+}diff --git a/nanobot/channels/weixin/webui/WeixinPanel.tsx b/nanobot/channels/weixin/webui/WeixinPanel.tsxindex 959f287a7..40cab931b 100644--- a/nanobot/channels/weixin/webui/WeixinPanel.tsx+++ b/nanobot/channels/weixin/webui/WeixinPanel.tsx@@ -1,41 +1,22 @@-import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";-import { Check, ChevronDown, Loader2, Plus } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import { channelFieldMessageKey, channelTranslator } from "@/channel-plugins/i18n";-import { channelLocaleMessages } from "@/channel-plugins/locale-registry";+import { channelTranslator } from "@/channel-plugins/i18n";import type { ChannelPluginPanelProps } from "@/channel-plugins/types";import {- type ChannelConfigField,-} from "@/channel-plugins/catalog";-import {- CredentialForm,channelValuesForSave,defaultChannelFieldValues,} from "@/components/settings/channels/CredentialForm";-import {- CHANNEL_SETUP_PANEL_CLASS_NAME,- ChannelLogo,-} from "@/components/settings/channels/ChannelIdentity";-import { Button } from "@/components/ui/button";-import { DisclosureContent } from "@/components/ui/disclosure";-import { normalizeLocale } from "@/i18n/config";import { configureChannel } from "@/lib/api";-import type {- ChannelSetupContractField,- NanobotFeatureInfo,-} from "@/lib/types";-import { cn } from "@/lib/utils";import { useClient } from "@/providers/ClientProvider";+import { WeixinConnectFlow } from "./WeixinConnectFlow";+import { WeixinPanelView } from "./WeixinPanelView";import {WEIXIN_AUTH_EXPIRED_MESSAGE,- WeixinConnectFlow,-} from "./WeixinConnectFlow";-import {- WEIXIN_ADVANCED_FIELD_KEYS,- WEIXIN_PRIMARY_FIELD_KEYS,- WEIXIN_QR_TOKEN_FIELD_KEY,+ localizeBooleanFields,+ weixinRuntimeError,+ weixinSetupFields,} from "./presentation";export function WeixinPanel({@@ -55,12 +36,6 @@ export function WeixinPanel({const [authRecoveryActive, setAuthRecoveryActive] = useState(authExpired);const runtimeError = weixinRuntimeError(feature.runtime_error, channelTx)?? (authRecoveryActive ? channelTx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE) : undefined);- const displayName = channelTx("displayName", "WeChat");- const enabledBusy = actionKey === `enable:${feature.name}`;- const missingSupport = feature.enabled && !feature.installed;- const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});- const [advancedOpen, setAdvancedOpen] = useState(false);- const advancedPanelId = useId();const [touchedFields, setTouchedFields] = useState<Set<string>>(() => new Set());const [saving, setSaving] = useState(false);const [saveRevision, setSaveRevision] = useState(0);@@ -115,7 +90,6 @@ export function WeixinPanel({}fieldValuesRef.current = nextValues;setFieldValues(nextValues);- setVisibleSecrets({});}, [configValuesKey, setupFieldsKey]);useEffect(() => {@@ -192,213 +166,29 @@ export function WeixinPanel({};return (- <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>- <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">- <div className="flex min-w-0 max-w-full items-center gap-3">- <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />- <h3 className="sr-only">{displayName}</h3>- {missingSupport && feature.install_supported ? (- <Button- type="button"- size="sm"- variant="secondary"- disabled={enabledBusy}- onClick={() => onAction("enable", feature.name)}- className="h-8 rounded-full px-3 text-[12px] font-semibold"- >- {enabledBusy ? (- <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />- ) : (- <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />- )}- {tx("settings.nanobotFeatures.installSupport", "Install support")}- </Button>- ) : null}- </div>- {advancedFields.length ? (- <button- type="button"- className="ms-auto 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>-- {runtimeError ? (- <div className="mt-4 rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive">- {runtimeError}- </div>- ) : null}-- <div className="mt-4 space-y-4">- <WeixinConnectFlow- token={token}- feature={feature}- authRecoveryActive={authRecoveryActive}- idleLabel={channelTx("setup.primaryAction", "Connect WeChat")}- connectRequestId={connectRequestId}- onFeaturesUpdate={onFeaturesUpdate}- />-- {primaryFields.length ? (- <CredentialForm- fields={primaryFields}- values={fieldValues}- configuredFields={configuredFields}- visibleSecrets={visibleSecrets}- onChange={setFieldValue}- onToggleSecret={(key) => {- setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));- }}- compact- />- ) : null}-- <div- role="status"- aria-live="polite"- aria-atomic="true"- className={cn(- "flex items-center justify-end gap-1.5 text-[11px] leading-4 text-muted-foreground",- !saving && saveState !== "saved" && "sr-only",- )}- >- {saving ? (- <>- <Loader2 className="h-3 w-3 animate-spin" aria-hidden />- {tx("settings.actions.saving", "Saving")}- </>- ) : saveState === "saved" ? (- <>- <Check className="h-3 w-3" aria-hidden />- {tx("settings.channels.savedSettings", "Saved settings.")}- </>- ) : null}- </div>-- {saveError ? (- <div- role="alert"- className="rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive"- >- {saveError}- </div>- ) : null}-- {advancedFields.length ? (- <DisclosureContent id={advancedPanelId} open={advancedOpen} className="text-[12px] leading-5 text-muted-foreground">- <CredentialForm- fields={advancedFields}- values={fieldValues}- configuredFields={configuredFields}- visibleSecrets={visibleSecrets}- onChange={setFieldValue}- onToggleSecret={(key) => {- setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));- }}- compact- />- </DisclosureContent>- ) : null}-- </div>- </aside>+ <WeixinPanelView+ feature={feature}+ actionKey={actionKey}+ showBrandLogos={showBrandLogos}+ primaryFields={primaryFields}+ advancedFields={advancedFields}+ fieldValues={fieldValues}+ configuredFields={configuredFields}+ secretVisibilityKey={`${configValuesKey}:${setupFieldsKey}`}+ runtimeError={runtimeError}+ saving={saving}+ saveState={saveState}+ saveError={saveError}+ connectFlow={<WeixinConnectFlow+ token={token}+ feature={feature}+ authRecoveryActive={authRecoveryActive}+ idleLabel={channelTx("setup.primaryAction", "Connect WeChat")}+ connectRequestId={connectRequestId}+ onFeaturesUpdate={onFeaturesUpdate}+ />}+ onInstall={() => onAction("enable", feature.name)}+ onFieldChange={setFieldValue}+ />);}--function weixinSetupFields(- feature: NanobotFeatureInfo,- locale: string,-): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } {- const fields = (feature.setup?.fields ?? []).filter(- (field) => field.key !== WEIXIN_QR_TOKEN_FIELD_KEY,- );- const fieldsByKey = new Map(fields.map((field) => [field.key, field]));- const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup;- const knownKeys = new Set<string>([- ...WEIXIN_PRIMARY_FIELD_KEYS,- ...WEIXIN_ADVANCED_FIELD_KEYS,- ]);- const extraKeys = fields- .map((field) => field.key)- .filter((key) => !knownKeys.has(key));- const hydrate = (keys: readonly string[]) => keys.flatMap((key) => {- const field = fieldsByKey.get(key);- if (!field) return [];- const copy = messages?.fields?.[channelFieldMessageKey("weixin", key)];- return [weixinConfigField(field, copy)];- });-- return {- primary: hydrate(WEIXIN_PRIMARY_FIELD_KEYS),- advanced: hydrate([...WEIXIN_ADVANCED_FIELD_KEYS, ...extraKeys]),- };-}--function weixinConfigField(- field: ChannelSetupContractField,- copy: { label: string; placeholder?: string; choices?: Record<string, string> }- | undefined,-): ChannelConfigField {- const choices = field.kind === "bool" ? ["true", "false"] : field.choices;- return {- key: field.key,- label: copy?.label ?? fieldLabel(field.field),- placeholder: copy?.placeholder,- secret: field.kind === "secret",- optional: !field.required,- inputType: field.kind === "int" ? "number" : undefined,- defaultValue: field.default_value,- options:- field.kind === "enum" || field.kind === "bool"- ? choices.map((choice) => ({- value: choice,- label: copy?.choices?.[choice] ?? fieldLabel(choice),- }))- : undefined,- };-}--function fieldLabel(value: string): string {- const spaced = value- .replace(/([a-z0-9])([A-Z])/g, "$1 $2")- .replace(/[_-]+/g, " ")- .trim();- return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;-}--function weixinRuntimeError(- error: string | undefined,- tx: (key: string, fallback: string) => string,-): string | undefined {- if (error === WEIXIN_AUTH_EXPIRED_MESSAGE) {- return tx("custom.expired", error);- }- return error;-}--function localizeBooleanFields(- fields: ChannelConfigField[],- onLabel: string,- offLabel: string,-): ChannelConfigField[] {- return fields.map((field) => {- const values = new Set(field.options?.map((option) => option.value));- if (values.size !== 2 || !values.has("true") || !values.has("false")) return field;- return {- ...field,- options: field.options?.map((option) => ({- ...option,- label: option.value === "true" ? onLabel : offLabel,- })),- };- });-}diff --git a/nanobot/channels/weixin/webui/WeixinPanelView.tsx b/nanobot/channels/weixin/webui/WeixinPanelView.tsxnew file mode 100644index 000000000..84678761a--- /dev/null+++ b/nanobot/channels/weixin/webui/WeixinPanelView.tsx@@ -0,0 +1,162 @@+import { useEffect, useId, useState, type ReactNode } from "react";+import { Check, ChevronDown, Loader2, Plus } from "lucide-react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import type { ChannelConfigField } from "@/channel-plugins/catalog";+import { CredentialForm } from "@/components/settings/channels/CredentialForm";+import { CHANNEL_SETUP_PANEL_CLASS_NAME, ChannelLogo } from "@/components/settings/channels/ChannelIdentity";+import { Button } from "@/components/ui/button";+import { DisclosureContent } from "@/components/ui/disclosure";+import type { NanobotFeatureInfo } from "@/lib/types";+import { cn } from "@/lib/utils";++export type WeixinPanelViewProps = {+ feature: NanobotFeatureInfo;+ actionKey: string | null;+ showBrandLogos: boolean;+ primaryFields: ChannelConfigField[];+ advancedFields: ChannelConfigField[];+ fieldValues: Record<string, string>;+ configuredFields: Set<string>;+ secretVisibilityKey: string;+ runtimeError?: string;+ saving: boolean;+ saveState: "idle" | "saved";+ saveError: string | null;+ connectFlow: ReactNode;+ onInstall: () => void;+ onFieldChange: (key: string, value: string) => void;+};++export function WeixinPanelView({+ feature, actionKey, showBrandLogos, primaryFields, advancedFields, fieldValues,+ configuredFields, secretVisibilityKey, runtimeError, saving, saveState, saveError,+ connectFlow, onInstall, onFieldChange,+}: WeixinPanelViewProps) {+ const { t } = useTranslation();+ const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });+ const channelTx = channelTranslator(t, "weixin");+ const displayName = channelTx("displayName", "WeChat");+ const enabledBusy = actionKey === `enable:${feature.name}`;+ const missingSupport = feature.enabled && !feature.installed;+ const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const advancedPanelId = useId();+ useEffect(() => setVisibleSecrets({}), [secretVisibilityKey]);++ return (+ <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pe-20">+ <div className="flex min-w-0 max-w-full items-center gap-3">+ <ChannelLogo feature={feature} showBrandLogos={showBrandLogos} />+ <h3 className="sr-only">{displayName}</h3>+ {missingSupport && feature.install_supported ? (+ <Button+ type="button"+ size="sm"+ variant="secondary"+ disabled={enabledBusy}+ onClick={onInstall}+ className="h-8 rounded-full px-3 text-[12px] font-semibold"+ >+ {enabledBusy ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />+ ) : (+ <Plus className="mr-1.5 h-3.5 w-3.5" aria-hidden />+ )}+ {tx("settings.nanobotFeatures.installSupport", "Install support")}+ </Button>+ ) : null}+ </div>+ {advancedFields.length ? (+ <button+ type="button"+ className="ms-auto 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>++ {runtimeError ? (+ <div role="alert" className="mt-4 rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive">+ {runtimeError}+ </div>+ ) : null}++ <div className="mt-4 space-y-4">+ {connectFlow}++ {primaryFields.length ? (+ <CredentialForm+ fields={primaryFields}+ values={fieldValues}+ configuredFields={configuredFields}+ visibleSecrets={visibleSecrets}+ onChange={onFieldChange}+ onToggleSecret={(key) => {+ setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));+ }}+ compact+ />+ ) : null}++ <div+ role="status"+ aria-live="polite"+ aria-atomic="true"+ className={cn(+ "flex items-center justify-end gap-1.5 text-[11px] leading-4 text-muted-foreground",+ !saving && saveState !== "saved" && "sr-only",+ )}+ >+ {saving ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />+ {tx("settings.actions.saving", "Saving")}+ </>+ ) : saveState === "saved" ? (+ <>+ <Check className="h-3 w-3" aria-hidden />+ {tx("settings.channels.savedSettings", "Saved settings.")}+ </>+ ) : null}+ </div>++ {saveError ? (+ <div+ role="alert"+ className="rounded-control border border-destructive/20 bg-destructive/5 px-3 py-2 text-[12px] leading-5 text-destructive"+ >+ {saveError}+ </div>+ ) : null}++ {advancedFields.length ? (+ <DisclosureContent id={advancedPanelId} open={advancedOpen} className="text-[12px] leading-5 text-muted-foreground">+ <CredentialForm+ fields={advancedFields}+ values={fieldValues}+ configuredFields={configuredFields}+ visibleSecrets={visibleSecrets}+ onChange={onFieldChange}+ onToggleSecret={(key) => {+ setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }));+ }}+ compact+ />+ </DisclosureContent>+ ) : null}++ </div>+ </aside>+ );+}diff --git a/nanobot/channels/weixin/webui/presentation.ts b/nanobot/channels/weixin/webui/presentation.tsindex f97913b16..421fadead 100644--- a/nanobot/channels/weixin/webui/presentation.ts+++ b/nanobot/channels/weixin/webui/presentation.ts@@ -1,3 +1,30 @@+import { channelFieldMessageKey } from "@/channel-plugins/i18n";+import { channelLocaleMessages } from "@/channel-plugins/locale-registry";+import type { ChannelConfigField } from "@/channel-plugins/catalog";+import { normalizeLocale } from "@/i18n/config";+import type { ChannelConnectPayload, ChannelSetupContractField, NanobotFeatureInfo } from "@/lib/types";++export const WEIXIN_AUTH_EXPIRED_MESSAGE =+ "WeChat login expired. Scan again to reconnect.";++export type WeixinVerificationPayload = ChannelConnectPayload & {+ challenge: "verify_code";+ verification_failed?: boolean;+};++export function isVerificationChallenge(+ payload: ChannelConnectPayload,+): payload is WeixinVerificationPayload {+ return (+ "challenge" in payload+ && payload.challenge === "verify_code"+ && (+ !("verification_failed" in payload)+ || typeof payload.verification_failed === "boolean"+ )+ );+}+export const WEIXIN_PRIMARY_FIELD_KEYS = ["channels.weixin.sendProgress","channels.weixin.sendToolHints",@@ -20,3 +47,92 @@ export const WEIXIN_ADVANCED_FIELD_KEYS = ["channels.weixin.stateDir","channels.weixin.pollTimeout",] as const;++export function weixinSetupFields(+ feature: NanobotFeatureInfo,+ locale: string,+): { primary: ChannelConfigField[]; advanced: ChannelConfigField[] } {+ const fields = (feature.setup?.fields ?? []).filter(+ (field) => field.key !== WEIXIN_QR_TOKEN_FIELD_KEY,+ );+ const fieldsByKey = new Map(fields.map((field) => [field.key, field]));+ const messages = channelLocaleMessages("weixin", normalizeLocale(locale))?.setup;+ const knownKeys = new Set<string>([+ ...WEIXIN_PRIMARY_FIELD_KEYS,+ ...WEIXIN_ADVANCED_FIELD_KEYS,+ ]);+ const extraKeys = fields+ .map((field) => field.key)+ .filter((key) => !knownKeys.has(key));+ const hydrate = (keys: readonly string[]) => keys.flatMap((key) => {+ const field = fieldsByKey.get(key);+ if (!field) return [];+ const copy = messages?.fields?.[channelFieldMessageKey("weixin", key)];+ return [weixinConfigField(field, copy)];+ });++ return {+ primary: hydrate(WEIXIN_PRIMARY_FIELD_KEYS),+ advanced: hydrate([...WEIXIN_ADVANCED_FIELD_KEYS, ...extraKeys]),+ };+}++function weixinConfigField(+ field: ChannelSetupContractField,+ copy: { label: string; placeholder?: string; choices?: Record<string, string> }+ | undefined,+): ChannelConfigField {+ const choices = field.kind === "bool" ? ["true", "false"] : field.choices;+ return {+ key: field.key,+ label: copy?.label ?? fieldLabel(field.field),+ placeholder: copy?.placeholder,+ secret: field.kind === "secret",+ optional: !field.required,+ inputType: field.kind === "int" ? "number" : undefined,+ defaultValue: field.default_value,+ options:+ field.kind === "enum" || field.kind === "bool"+ ? choices.map((choice) => ({+ value: choice,+ label: copy?.choices?.[choice] ?? fieldLabel(choice),+ }))+ : undefined,+ };+}++function fieldLabel(value: string): string {+ const spaced = value+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")+ .replace(/[_-]+/g, " ")+ .trim();+ return spaced ? spaced[0].toUpperCase() + spaced.slice(1) : value;+}++export function weixinRuntimeError(+ error: string | undefined,+ tx: (key: string, fallback: string) => string,+): string | undefined {+ if (error === WEIXIN_AUTH_EXPIRED_MESSAGE) {+ return tx("custom.expired", error);+ }+ return error;+}++export function localizeBooleanFields(+ fields: ChannelConfigField[],+ onLabel: string,+ offLabel: string,+): ChannelConfigField[] {+ return fields.map((field) => {+ const values = new Set(field.options?.map((option) => option.value));+ if (values.size !== 2 || !values.has("true") || !values.has("false")) return field;+ return {+ ...field,+ options: field.options?.map((option) => ({+ ...option,+ label: option.value === "true" ? onLabel : offLabel,+ })),+ };+ });+}diff --git a/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsxindex c4ba7d895..b6311df2b 100644--- a/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx+++ b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlow.tsx@@ -1,17 +1,15 @@-import { useTranslation } from "react-i18next";--import { channelTranslator } from "@/channel-plugins/i18n";import type { ChannelPluginConnectFlowProps } from "@/channel-plugins/types";import { ChannelQrConnectFlow } from "@/components/settings/channels/ChannelQrConnectFlow";+import { WhatsAppConnectFlowView, useWhatsAppConnectLabels } from "./WhatsAppConnectFlowView";+export function WhatsAppConnectFlow({token,idleLabel,connectRequestId,onFeaturesUpdate,}: ChannelPluginConnectFlowProps) {- const { t } = useTranslation();- const tx = channelTranslator(t, "whatsapp");+ const labels = useWhatsAppConnectLabels();return (<ChannelQrConnectFlow@@ -22,23 +20,8 @@ export function WhatsAppConnectFlow({autoStartminimalPendingforceOnRepeat- labels={{- qrAlt: tx("custom.qrAlt", "WhatsApp linking QR code"),- scanTitle: tx("custom.scanTitle", "Link WhatsApp"),- scanDescription: tx(- "custom.scanDescription",- "In WhatsApp, open Linked devices, choose Link a device, then scan this code.",- ),- waiting: tx("custom.waiting", "Waiting for WhatsApp…"),- connected: tx("custom.connected", "WhatsApp is connected."),- stopped: tx(- "custom.stopped",- "The WhatsApp connection attempt stopped. Start again to get a new code.",- ),- connecting: tx("custom.connecting", "Connecting…"),- scanAgain: tx("custom.scanAgain", "Link another account"),- connect: tx("custom.connect", "Link WhatsApp"),- }}+ labels={labels}+ renderView={(props) => <WhatsAppConnectFlowView {...props} />}onFeaturesUpdate={onFeaturesUpdate}/>);diff --git a/nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsx b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsxnew file mode 100644index 000000000..c7267a7e0--- /dev/null+++ b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsx@@ -0,0 +1,33 @@+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { ChannelQrConnectFlowView, type ChannelQrConnectFlowViewProps, type ChannelQrConnectLabels } from "@/components/settings/channels/ChannelQrConnectFlowView";++export type WhatsAppConnectFlowViewProps = Omit<ChannelQrConnectFlowViewProps, "labels" | "autoStart" | "minimalPending">;++export function useWhatsAppConnectLabels(): ChannelQrConnectLabels {+ const { t } = useTranslation();+ const tx = channelTranslator(t, "whatsapp");+ return {+ qrAlt: tx("custom.qrAlt", "WhatsApp linking QR code"),+ scanTitle: tx("custom.scanTitle", "Link WhatsApp"),+ scanDescription: tx(+ "custom.scanDescription",+ "In WhatsApp, open Linked devices, choose Link a device, then scan this code.",+ ),+ waiting: tx("custom.waiting", "Waiting for WhatsApp…"),+ connected: tx("custom.connected", "WhatsApp is connected."),+ stopped: tx(+ "custom.stopped",+ "The WhatsApp connection attempt stopped. Start again to get a new code.",+ ),+ connecting: tx("custom.connecting", "Connecting…"),+ scanAgain: tx("custom.scanAgain", "Link another account"),+ connect: tx("custom.connect", "Link WhatsApp"),+ };+}++export function WhatsAppConnectFlowView(props: WhatsAppConnectFlowViewProps) {+ const labels = useWhatsAppConnectLabels();+ return <ChannelQrConnectFlowView {...props} labels={labels} autoStart minimalPending />;+}diff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.mdnew file mode 100644index 000000000..7e94bf520--- /dev/null+++ b/webui/COMPONENTS.md@@ -0,0 +1,76 @@+# WebUI components++## Browse the internal gallery++From `webui/`, run:++```sh+bun install --frozen-lockfile+bun run gallery+```++Open `http://127.0.0.1:5173/gallery.html`. The gallery uses the existing Vite development server and the actual application components. It needs no gateway, model provider, or API key. If another Vite server occupies the default port, use `bun run gallery --port 5174`.++The gallery opens in **Previews**, which lists components with working examples. **All source** includes the complete source inventory and marks entries as **Preview** or **Source only**. Source-only entries link to related previews when their direct imports or callers have examples. A bookmarked source-only entry opens the source index automatically.++Search by module name, exported name, path, or the bilingual example title. Categories separate foundation controls, shared views, conversation, settings, hosts, workbench, icons, and channel-owned interfaces. Each entry shows its source, exports, and direct references. The selected entry is kept in the URL, so it can be bookmarked or reloaded.++The inventory is read from the current checkout. **Refresh inventory** picks up added, removed, and changed source files. Counts are source-module counts: a module can export several components, and several modules can belong to one example family. Direct references include imports, literal dynamic imports, and re-exports, including type references; they exclude tests and the gallery. Indirect plugin registration is not a direct reference, so an empty reference list does not prove that a component is unused.++All foundation controls have live examples. Shared examples cover Markdown, code, math, messages, media, thinking/tool activity, file edits, and file references. Settings examples include the provider management dialog with its search and configuration flow, model controls, capability forms, channel credentials, usage charts, and automation controls. Conversation examples include the composer, prompt navigation, activity and error states. Shell examples include conversation dialogs, mentions, host status, icons, and pane layouts. These examples mount the product components with local data and caller-owned actions.++Change state selectors to inspect streaming, completion, disabled, missing-media, or error states where applicable. Dialog and disclosure examples preserve local drafts; their actions affect only the preview. Use the header to change theme and the language of the product components. Gallery explanations and code examples are development documentation.++Feature screens that own gateway requests, session state, or host connections are indexed with their source and callers. Exercise their complete workflows in the running WebUI. The gallery does not emulate those services.++Runtime adapters and presentation views have separate responsibilities. Adapters subscribe to clients, load data, enforce browser restrictions, and perform service actions. Their views receive display data and operation callbacks. Production screens and gallery examples mount the same views, including host menus, pairing, file/web previews, session tasks, automation results, version information, and notification preferences. Connected source entries link to the corresponding view examples.++Every channel registration has a preview. Channels with shared configuration forms use their production setup view; Linear, Feishu, Weixin, and WhatsApp use their channel-owned views, including authorization, verification, assistant management, and connection reset. The source inventory includes channel `webui/index.ts` registrations as well as `.tsx` components. Connected adapters link to the views they own.++Channel fixture fields, defaults, and requirements come from the Python channel setup contracts. Regenerate `src/dev/gallery/channel-fixtures.ts` with `python webui/src/dev/gallery/generate_channel_fixtures.py` from the repository root after changing those contracts; add `--check` to verify the snapshot. This developer command loads channel descriptors without starting a gateway. Running the gallery uses the committed snapshot and requires no Python process.++## Where components belong++| Location | Ownership | Examples |+| --- | --- | --- |+| `src/components/ui/` | Foundation controls and small presentation primitives shared across features | `Button`, `Input`, `ToggleButton`, dialog/menu/tooltip primitives, `StreamingLabelSheen` |+| `src/components/` | Shared content renderers and application-shell compositions | `MarkdownText`, `CodeBlock`, `ImageGallery`, `MessageBubble`, `Sidebar` |+| `src/components/thread/` | Conversation UI and its display models | Composer, viewport, prompt navigation, activity rows |+| `src/components/settings/shared/` | Reusable settings-specific compositions | Settings rows/groups, feature editors, provider controls |+| `src/components/settings/` | Settings feature screens and their controllers | Models, capabilities, channels, automations |+| `src/components/remote/` | Host selection and connection interfaces | Host switcher, pairing and remote connections |+| `src/components/workbench/` | Pane layout and its interaction model | `PaneWorkbench` |+| `src/components/icons/` | Product-specific icon vocabulary | `product-icons.tsx` |+| `nanobot/channels/<channel>/webui/` | Channel-owned screens, components, and translations | Feishu assistants, Linear setup, Weixin connection |++Supporting hooks and display-model helpers stay near the feature that owns them. Common theme tokens and reusable CSS treatments live in `src/globals.css`, `tailwind.config.js`, and the relevant `ui/` modules. The component inventory lists `.tsx` modules; pure `.ts` helpers remain discoverable through their callers and source imports.++## Choose an existing component++- Check the gallery and current callers before creating a control. Different labels, colors, or sizes usually call for an existing component's options. `Button` already has appearance and size variants; `Input` and `SearchInput` share the input implementation.+- Compose controls for a larger interaction. A settings row owns its layout, while the switch or text field supplies its own focus, disabled, and keyboard behavior.+- Extract a shared component when current callers need the same behavior. Keep feature-specific state and actions in the owning screen. A reusable animation should not import an entire message renderer, and a foundation control should not depend on a settings screen.+- Preserve meaningful differences. A one-shot action and an on/off switch have different interaction contracts even when their silhouettes look similar. Use `className` for local placement; put a shared appearance change in the component or token that owns it.+- Keep agent execution, sessions, tools, memory, and security policy in the Python gateway. UI components receive display data and caller-owned actions.++For example, a caller controls a shared switch:++```tsx+import { ToggleButton } from "@/components/ui/toggle-button";++<ToggleButton+ checked={enabled}+ onChange={setEnabled}+ label="Enable feature"+/>+```++The caller decides how to persist `enabled`; the switch implements the interaction and appearance.++## Maintain the gallery++The development entry is `gallery.html`; its UI and examples live in `src/dev/gallery/`. The Vite `componentGallery` plugin serves the source inventory only during development. The normal production build starts at `index.html` and excludes the gallery entry, inventory endpoint, and source-view data.++Add examples to the appropriate feature file in `src/dev/gallery/`. Each example names the source modules it actually renders, describes the useful options, and contains a small usage snippet. Mount the actual component and use local state for interactions. Supply fixture data through the component's existing props. When a reusable interface owns client subscriptions or service requests, separate its presentation view from the owning adapter and use that view in production and the gallery. Combine related modules into one example rather than exposing every implementation detail as a separate control. A coverage test checks that every foundation module has an example and that all example source paths exist.++Run the focused gallery and affected component tests, lint, and `bun run build`. The build type-checks the gallery source even though it does not bundle it. Inspect examples in light/dark themes and at narrow widths, exercise keyboard interaction, and verify the affected production screens through the gateway.diff --git a/webui/README.md b/webui/README.mdindex ccd35a465..84abbbedf 100644--- a/webui/README.md+++ b/webui/README.md@@ -17,6 +17,8 @@ The source app is built with Vite + React 18 + TypeScript + Tailwind 3 + shadcn/## Layout+For existing components, ownership boundaries, and interactive examples, see the [component guide](COMPONENTS.md). `bun run gallery` opens the internal component gallery without starting a gateway.+```textwebui/ source tree (this directory)nanobot/web/dist/ build output served by the gatewaydiff --git a/webui/bun.lock b/webui/bun.lockindex 81a57d874..7f4af13f1 100644--- a/webui/bun.lock+++ b/webui/bun.lock@@ -539,7 +539,7 @@"balanced-match": ["[email protected]", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],- "baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g=="],+ "baseline-browser-mapping": ["[email protected]", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-br0LOmjJqr6Rt4AEkadbcNf67Zpo7EPwKsWbjnRrJIa1QYFHQBqM4C7F2WTbV8ahTEcg1Eo+Y0aWjjORInYFyA=="],"binary-extensions": ["[email protected]", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="],@@ -555,7 +555,7 @@"camelcase-css": ["[email protected]", "", {}, "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA=="],- "caniuse-lite": ["[email protected]", "", {}, "sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ=="],+ "caniuse-lite": ["[email protected]", "", {}, "sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q=="],"ccount": ["[email protected]", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="],diff --git a/webui/gallery.html b/webui/gallery.htmlnew file mode 100644index 000000000..2f3f0b2f7--- /dev/null+++ b/webui/gallery.html@@ -0,0 +1,13 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Nanobot component gallery</title>+ <link rel="icon" href="/brand/nanobot_favicon_32.png" />+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/dev/gallery/main.tsx"></script>+ </body>+</html>diff --git a/webui/package-lock.json b/webui/package-lock.jsonindex dfc7fe783..38099fab3 100644--- a/webui/package-lock.json+++ b/webui/package-lock.json@@ -3505,7 +3505,7 @@}},"node_modules/baseline-browser-mapping": {- "version": "2.10.19",+ "version": "2.11.28","dev": true,"license": "Apache-2.0","bin": {@@ -3608,7 +3608,7 @@}},"node_modules/caniuse-lite": {- "version": "1.0.30001788",+ "version": "1.0.30001815","dev": true,"funding": [{diff --git a/webui/package.json b/webui/package.jsonindex 66f89439d..09ddbe585 100644--- a/webui/package.json+++ b/webui/package.json@@ -5,6 +5,7 @@"type": "module","scripts": {"dev": "vite",+ "gallery": "vite --open /gallery.html","build": "tsc -p tsconfig.build.json && vite build","preview": "vite preview","test": "vitest run",diff --git a/webui/src/components/ConnectionBadge.tsx b/webui/src/components/ConnectionBadge.tsxindex a09aadd28..8bd4f3023 100644--- a/webui/src/components/ConnectionBadge.tsx+++ b/webui/src/components/ConnectionBadge.tsx@@ -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 =diff --git a/webui/src/components/FilePreviewPanel.tsx b/webui/src/components/FilePreviewPanel.tsxindex b9541aee7..0e57b4309 100644--- a/webui/src/components/FilePreviewPanel.tsx+++ b/webui/src/components/FilePreviewPanel.tsx@@ -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} />;}diff --git a/webui/src/components/FilePreviewPanelView.tsx b/webui/src/components/FilePreviewPanelView.tsxnew file mode 100644index 000000000..04d570252--- /dev/null+++ b/webui/src/components/FilePreviewPanelView.tsx@@ -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>+ );+}diff --git a/webui/src/components/StarPrompt.tsx b/webui/src/components/StarPrompt.tsxindex dbb296945..9872d4415 100644--- a/webui/src/components/StarPrompt.tsx+++ b/webui/src/components/StarPrompt.tsx@@ -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 });+ }} />;}diff --git a/webui/src/components/StarPromptView.tsx b/webui/src/components/StarPromptView.tsxnew file mode 100644index 000000000..9ac6250e1--- /dev/null+++ b/webui/src/components/StarPromptView.tsx@@ -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>+ );+}diff --git a/webui/src/components/WebPreviewPanel.tsx b/webui/src/components/WebPreviewPanel.tsxindex feed67ca8..50a0e8feb 100644--- a/webui/src/components/WebPreviewPanel.tsx+++ b/webui/src/components/WebPreviewPanel.tsx@@ -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>;}diff --git a/webui/src/components/WebPreviewPanelView.tsx b/webui/src/components/WebPreviewPanelView.tsxnew file mode 100644index 000000000..64b1a34a5--- /dev/null+++ b/webui/src/components/WebPreviewPanelView.tsx@@ -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>+ );+}diff --git a/webui/src/components/remote/HostSwitcher.tsx b/webui/src/components/remote/HostSwitcher.tsxindex eb8efda94..b9030dc6f 100644--- a/webui/src/components/remote/HostSwitcher.tsx+++ b/webui/src/components/remote/HostSwitcher.tsx@@ -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";--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);--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]);+import { HostNavigationContext } from "./host-navigation";+import { HostSwitcherView } from "./HostSwitcherView";- 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>;-}+export { HostNavigationContext, type HostPicker } from "./host-navigation";+export { RemoteHostMenu } from "./HostSwitcherView";-/** 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} />;}diff --git a/webui/src/components/remote/HostSwitcherView.tsx b/webui/src/components/remote/HostSwitcherView.tsxnew file mode 100644index 000000000..ca7ee23eb--- /dev/null+++ b/webui/src/components/remote/HostSwitcherView.tsx@@ -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>;+}diff --git a/webui/src/components/remote/PairRouteSettings.tsx b/webui/src/components/remote/PairRouteSettings.tsxindex 3dc67e3ae..7b89f6dde 100644--- a/webui/src/components/remote/PairRouteSettings.tsx+++ b/webui/src/components/remote/PairRouteSettings.tsx@@ -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: stringif (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(); }} />;}diff --git a/webui/src/components/remote/PairRouteSettingsView.tsx b/webui/src/components/remote/PairRouteSettingsView.tsxnew file mode 100644index 000000000..92b379262--- /dev/null+++ b/webui/src/components/remote/PairRouteSettingsView.tsx@@ -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>;+}diff --git a/webui/src/components/remote/QuickPairSetup.tsx b/webui/src/components/remote/QuickPairSetup.tsxindex a012e88bc..94bdb423e 100644--- a/webui/src/components/remote/QuickPairSetup.tsx+++ b/webui/src/components/remote/QuickPairSetup.tsx@@ -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 }: { reconst [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 }: { reelse { 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} />;}diff --git a/webui/src/components/remote/QuickPairSetupView.tsx b/webui/src/components/remote/QuickPairSetupView.tsxnew file mode 100644index 000000000..6e0efc875--- /dev/null+++ b/webui/src/components/remote/QuickPairSetupView.tsx@@ -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>;+}diff --git a/webui/src/components/remote/SSHHostPicker.tsx b/webui/src/components/remote/SSHHostPicker.tsxindex 02f0050c5..aae92fac3 100644--- a/webui/src/components/remote/SSHHostPicker.tsx+++ b/webui/src/components/remote/SSHHostPicker.tsx@@ -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";-/** 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;+type SSHHostPickerProps = Pick<SSHHostPickerViewProps,+ "disabled" | "value" | "imported" | "suggestions" | "onChange" | "onBlur" | "inputRef"> & {configFile: string;- imported: boolean;- suggestions?: boolean;- onChange: (host: string) => void;- onBlur: () => void;- inputRef: RefObject<HTMLInputElement>;-}) {+};++/** One address field for both manual entry and existing SSH aliases. */+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); }} />;}diff --git a/webui/src/components/remote/SSHHostPickerView.tsx b/webui/src/components/remote/SSHHostPickerView.tsxnew file mode 100644index 000000000..27876073f--- /dev/null+++ b/webui/src/components/remote/SSHHostPickerView.tsx@@ -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>;+}diff --git a/webui/src/components/remote/host-navigation.ts b/webui/src/components/remote/host-navigation.tsnew file mode 100644index 000000000..7d4a00e72--- /dev/null+++ b/webui/src/components/remote/host-navigation.ts@@ -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);diff --git a/webui/src/components/settings/SkillsCatalogSettings.tsx b/webui/src/components/settings/SkillsCatalogSettings.tsxindex 28ca15495..ab340858d 100644--- a/webui/src/components/settings/SkillsCatalogSettings.tsx+++ b/webui/src/components/settings/SkillsCatalogSettings.tsx@@ -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";diff --git a/webui/src/components/settings/capabilities/ImageGenerationSettings.tsx b/webui/src/components/settings/capabilities/ImageGenerationSettings.tsxindex feb23f7e8..2366dd6db 100644--- a/webui/src/components/settings/capabilities/ImageGenerationSettings.tsx+++ b/webui/src/components/settings/capabilities/ImageGenerationSettings.tsx@@ -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";diff --git a/webui/src/components/settings/capabilities/SecuritySettings.tsx b/webui/src/components/settings/capabilities/SecuritySettings.tsxindex dc7fda58d..e71d28b51 100644--- a/webui/src/components/settings/capabilities/SecuritySettings.tsx+++ b/webui/src/components/settings/capabilities/SecuritySettings.tsx@@ -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,diff --git a/webui/src/components/settings/capabilities/TranscriptionSettings.tsx b/webui/src/components/settings/capabilities/TranscriptionSettings.tsxindex b062c1c23..e3df98ed5 100644--- a/webui/src/components/settings/capabilities/TranscriptionSettings.tsx+++ b/webui/src/components/settings/capabilities/TranscriptionSettings.tsx@@ -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";diff --git a/webui/src/components/settings/capabilities/WebSettings.tsx b/webui/src/components/settings/capabilities/WebSettings.tsxindex 6a3221cd0..e11868534 100644--- a/webui/src/components/settings/capabilities/WebSettings.tsx+++ b/webui/src/components/settings/capabilities/WebSettings.tsx@@ -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 {diff --git a/webui/src/components/settings/channels/ChannelCatalogRow.tsx b/webui/src/components/settings/channels/ChannelCatalogRow.tsxindex 55d25f10f..55cbb5e64 100644--- a/webui/src/components/settings/channels/ChannelCatalogRow.tsx+++ b/webui/src/components/settings/channels/ChannelCatalogRow.tsx@@ -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,diff --git a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx b/webui/src/components/settings/channels/ChannelInstancesPanel.tsxindex 23d4d3e31..9077cfe9a 100644--- a/webui/src/components/settings/channels/ChannelInstancesPanel.tsx+++ b/webui/src/components/settings/channels/ChannelInstancesPanel.tsx@@ -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);- }- };-- 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);- }+ },+ 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);+ },};-- 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} />;}diff --git a/webui/src/components/settings/channels/ChannelInstancesPanelView.tsx b/webui/src/components/settings/channels/ChannelInstancesPanelView.tsxnew file mode 100644index 000000000..ea5afe27e--- /dev/null+++ b/webui/src/components/settings/channels/ChannelInstancesPanelView.tsx@@ -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] : [];+ });+}diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsxindex 3967830bb..eda9c6991 100644--- a/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx+++ b/webui/src/components/settings/channels/ChannelQrConnectFlow.tsx@@ -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} />;}diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsxnew file mode 100644index 000000000..c863fb386--- /dev/null+++ b/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx@@ -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>+ );+}diff --git a/webui/src/components/settings/channels/ChannelSetupPanel.tsx b/webui/src/components/settings/channels/ChannelSetupPanel.tsxindex 2e119855f..23feefe3b 100644--- a/webui/src/components/settings/channels/ChannelSetupPanel.tsx+++ b/webui/src/components/settings/channels/ChannelSetupPanel.tsx@@ -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 }) {diff --git a/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx b/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsxnew file mode 100644index 000000000..4e46e2c4f--- /dev/null+++ b/webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx@@ -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>+ );+}diff --git a/webui/src/components/settings/models/ModelAPIControl.tsx b/webui/src/components/settings/models/ModelAPIControl.tsxindex c6cad4022..45d718b9b 100644--- a/webui/src/components/settings/models/ModelAPIControl.tsx+++ b/webui/src/components/settings/models/ModelAPIControl.tsx@@ -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";diff --git a/webui/src/components/settings/models/ModelsSettings.tsx b/webui/src/components/settings/models/ModelsSettings.tsxindex 7974c4cd5..f8d268468 100644--- a/webui/src/components/settings/models/ModelsSettings.tsx+++ b/webui/src/components/settings/models/ModelsSettings.tsx@@ -4,7 +4,7 @@ import { useAutomaticModelAPI } from "@/components/settings/models/useAutomaticMimport { 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 {diff --git a/webui/src/components/settings/models/ProviderAPIControl.tsx b/webui/src/components/settings/models/ProviderAPIControl.tsxindex 6c856f315..0c301d0fe 100644--- a/webui/src/components/settings/models/ProviderAPIControl.tsx+++ b/webui/src/components/settings/models/ProviderAPIControl.tsx@@ -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";diff --git a/webui/src/components/settings/models/ProviderSettings.tsx b/webui/src/components/settings/models/ProviderSettings.tsxindex 40e55da4a..e139304c1 100644--- a/webui/src/components/settings/models/ProviderSettings.tsx+++ b/webui/src/components/settings/models/ProviderSettings.tsx@@ -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";diff --git a/webui/src/components/settings/overview/AboutSettingsView.tsx b/webui/src/components/settings/overview/AboutSettingsView.tsxnew file mode 100644index 000000000..c2532bc2f--- /dev/null+++ b/webui/src/components/settings/overview/AboutSettingsView.tsx@@ -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>+ );+}diff --git a/webui/src/components/settings/overview/AppearanceSettingsView.tsx b/webui/src/components/settings/overview/AppearanceSettingsView.tsxnew file mode 100644index 000000000..e636312a4--- /dev/null+++ b/webui/src/components/settings/overview/AppearanceSettingsView.tsx@@ -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>+ );+}diff --git a/webui/src/components/settings/overview/OverviewSettings.tsx b/webui/src/components/settings/overview/OverviewSettings.tsxindex 162f80ae6..fd47dce61 100644--- a/webui/src/components/settings/overview/OverviewSettings.tsx+++ b/webui/src/components/settings/overview/OverviewSettings.tsx@@ -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({diff --git a/webui/src/components/settings/overview/VersionCheckRowView.tsx b/webui/src/components/settings/overview/VersionCheckRowView.tsxnew file mode 100644index 000000000..d51cc1b0a--- /dev/null+++ b/webui/src/components/settings/overview/VersionCheckRowView.tsx@@ -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>+ );+}diff --git a/webui/src/components/settings/shared/SettingsAddButton.tsx b/webui/src/components/settings/shared/SettingsAddButton.tsxdeleted file mode 100644index ab2c6f1c8..000000000--- a/webui/src/components/settings/shared/SettingsAddButton.tsx+++ /dev/null@@ -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";diff --git a/webui/src/components/settings/shared/SettingsFeature.tsx b/webui/src/components/settings/shared/SettingsFeature.tsxindex cd30ddbdf..ce275a49c 100644--- a/webui/src/components/settings/shared/SettingsFeature.tsx+++ b/webui/src/components/settings/shared/SettingsFeature.tsx@@ -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";diff --git a/webui/src/components/settings/system/AutomationCalendar.tsx b/webui/src/components/settings/system/AutomationCalendar.tsxindex a3e78df9b..239c32483 100644--- a/webui/src/components/settings/system/AutomationCalendar.tsx+++ b/webui/src/components/settings/system/AutomationCalendar.tsx@@ -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>);}diff --git a/webui/src/components/settings/system/AutomationChatBinding.tsx b/webui/src/components/settings/system/AutomationChatBinding.tsxindex 5e784416f..db33aaa34 100644--- a/webui/src/components/settings/system/AutomationChatBinding.tsx+++ b/webui/src/components/settings/system/AutomationChatBinding.tsx@@ -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";--export type ChangeAutomationChat = (job: SessionAutomationJob, values: AutomationChatUpdate) => Promise<void>;-export type AutomationChatNames = ReadonlyMap<string, { title: string; handle: string }>;+import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";-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>;}diff --git a/webui/src/components/settings/system/AutomationChatBindingView.tsx b/webui/src/components/settings/system/AutomationChatBindingView.tsxnew file mode 100644index 000000000..cf112144f--- /dev/null+++ b/webui/src/components/settings/system/AutomationChatBindingView.tsx@@ -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>+ </>;+}diff --git a/webui/src/components/settings/system/AutomationRunDialog.tsx b/webui/src/components/settings/system/AutomationRunDialog.tsxindex 5fbe244e2..b297aaeb1 100644--- a/webui/src/components/settings/system/AutomationRunDialog.tsx+++ b/webui/src/components/settings/system/AutomationRunDialog.tsx@@ -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, onOpenonOpenChange: (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, onOpenreturn () => 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} />;}diff --git a/webui/src/components/settings/system/AutomationRunDialogView.tsx b/webui/src/components/settings/system/AutomationRunDialogView.tsxnew file mode 100644index 000000000..3f2d44f29--- /dev/null+++ b/webui/src/components/settings/system/AutomationRunDialogView.tsx@@ -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>+ );+}diff --git a/webui/src/components/settings/system/AutomationsSettings.tsx b/webui/src/components/settings/system/AutomationsSettings.tsxindex c2c313270..6c0d527e0 100644--- a/webui/src/components/settings/system/AutomationsSettings.tsx+++ b/webui/src/components/settings/system/AutomationsSettings.tsx@@ -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}diff --git a/webui/src/components/settings/system/RuntimeConfigSettings.tsx b/webui/src/components/settings/system/RuntimeConfigSettings.tsxindex cf9359c4a..c2713c10c 100644--- a/webui/src/components/settings/system/RuntimeConfigSettings.tsx+++ b/webui/src/components/settings/system/RuntimeConfigSettings.tsx@@ -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";diff --git a/webui/src/components/thread/SessionInfoPopover.tsx b/webui/src/components/thread/SessionInfoPopover.tsxindex bd57df81c..851eb9e15 100644--- a/webui/src/components/thread/SessionInfoPopover.tsx+++ b/webui/src/components/thread/SessionInfoPopover.tsx@@ -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" />;}diff --git a/webui/src/components/thread/SessionInfoPopoverView.tsx b/webui/src/components/thread/SessionInfoPopoverView.tsxnew file mode 100644index 000000000..bac16bd6c--- /dev/null+++ b/webui/src/components/thread/SessionInfoPopoverView.tsx@@ -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");+}diff --git a/webui/src/components/thread/SubagentThread.tsx b/webui/src/components/thread/SubagentThread.tsxindex 2522717ee..b168b31ea 100644--- a/webui/src/components/thread/SubagentThread.tsx+++ b/webui/src/components/thread/SubagentThread.tsx@@ -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} />;}diff --git a/webui/src/components/thread/SubagentThreadView.tsx b/webui/src/components/thread/SubagentThreadView.tsxnew file mode 100644index 000000000..ea6f7fe7c--- /dev/null+++ b/webui/src/components/thread/SubagentThreadView.tsx@@ -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} />+ </>;+}diff --git a/webui/src/components/thread/WorkspaceControls.tsx b/webui/src/components/thread/WorkspaceControls.tsxindex 3f309a927..c11cd74fe 100644--- a/webui/src/components/thread/WorkspaceControls.tsx+++ b/webui/src/components/thread/WorkspaceControls.tsx@@ -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";diff --git a/webui/src/components/thread/useSubagentThread.ts b/webui/src/components/thread/useSubagentThread.tsnew file mode 100644index 000000000..ab61db616--- /dev/null+++ b/webui/src/components/thread/useSubagentThread.ts@@ -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 };+}diff --git a/webui/src/components/settings/ToggleButton.tsx b/webui/src/components/ui/toggle-button.tsxsimilarity index 100%rename from webui/src/components/settings/ToggleButton.tsxrename to webui/src/components/ui/toggle-button.tsxdiff --git a/webui/src/dev/gallery/Gallery.tsx b/webui/src/dev/gallery/Gallery.tsxnew file mode 100644index 000000000..e2d382fbe--- /dev/null+++ b/webui/src/dev/gallery/Gallery.tsx@@ -0,0 +1,174 @@+import { useEffect, useState } from "react";++import { Button } from "@/components/ui/button";+import { SearchInput } from "@/components/ui/input";+import { LanguageSwitcher } from "@/components/LanguageSwitcher";+import { SegmentedControl } from "@/components/ui/segmented-control";+import { ToggleButton } from "@/components/ui/toggle-button";+import { ThemeProvider, useTheme } from "@/hooks/useTheme";+import { cn } from "@/lib/utils";+import { foundationExamples } from "./foundations";+import { sharedExamples } from "./shared-views";+import { settingsExamples } from "./settings";+import { providerExamples } from "./providers";+import { conversationExamples } from "./conversation";+import { shellExamples } from "./shell";+import { standaloneExamples } from "./standalone";+import { remoteExamples } from "./remote";+import { contentExamples } from "./content";+import { runtimeSettingsExamples } from "./runtime-settings";+import { channelExamples, withChannelEntries } from "./channels";+import { feishuWhatsAppChannelExamples } from "./channels-feishu-whatsapp";+import { linearChannelExamples } from "./channels-linear";+import { weixinChannelExamples } from "./channels-weixin";+import { foundationPath, type ComponentSource } from "./inventory";++export const examples = [...foundationExamples, ...sharedExamples, ...settingsExamples, ...providerExamples, ...conversationExamples, ...shellExamples, ...standaloneExamples, ...remoteExamples, ...contentExamples, ...runtimeSettingsExamples,+ ...channelExamples, ...withChannelEntries([...feishuWhatsAppChannelExamples, ...linearChannelExamples, ...weixinChannelExamples])];+const examplesByPath = new Map(examples.flatMap((example) => example.files.map((file) => [file, example] as const)));++function selectedPath(): string {+ return new URLSearchParams(window.location.hash.slice(1)).get("component") ?? `${foundationPath}button.tsx`;+}++export function Gallery() {+ const { theme, setTheme } = useTheme();+ const [inventory, setInventory] = useState<ComponentSource[]>([]);+ const [error, setError] = useState("");+ const [loading, setLoading] = useState(true);+ const [reload, setReload] = useState(0);+ const [query, setQuery] = useState("");+ const [group, setGroup] = useState("All");+ const [selected, setSelected] = useState(selectedPath);+ const [view, setView] = useState<"previews" | "all">(() => examplesByPath.has(selectedPath()) ? "previews" : "all");++ useEffect(() => {+ const controller = new AbortController();+ setLoading(true);+ setError("");+ void fetch("/__nanobot_components", { signal: controller.signal })+ .then(async (response) => {+ if (!response.ok) throw new Error("Could not load the inventory. Check the Vite terminal and retry.");+ const data: ComponentSource[] = await response.json();+ setInventory(data);+ })+ .catch((reason: unknown) => {+ if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : String(reason));+ })+ .finally(() => { if (!controller.signal.aborted) setLoading(false); });+ return () => controller.abort();+ }, [reload]);++ useEffect(() => {+ const change = () => {+ const next = selectedPath();+ setSelected(next);+ if (!examplesByPath.has(next)) setView("all");+ };+ window.addEventListener("hashchange", change);+ return () => window.removeEventListener("hashchange", change);+ }, []);++ const previewCount = inventory.filter((item) => examplesByPath.has(item.path)).length;+ const browsable = view === "previews" ? inventory.filter((item) => examplesByPath.has(item.path)) : inventory;+ const groups = ["All", ...new Set(browsable.map((item) => item.group))];+ const search = query.trim().toLowerCase();+ const filtered = browsable.filter((item) => (group === "All" || item.group === group)+ && `${item.path} ${item.exports.join(" ")} ${examplesByPath.get(item.path)?.title ?? ""}`.toLowerCase().includes(search));+ const current = browsable.find((item) => item.path === selected) ?? browsable[0];+ const example = current && examplesByPath.get(current.path);+ const relatedExamples = current && !example ? examples.filter((item) => item.files.some((file) =>+ current.usedBy.includes(file) || inventory.find((source) => source.path === file)?.usedBy.includes(current.path))) : [];++ return <ThemeProvider theme={theme}>+ <div className="component-gallery">+ <header className="gallery-header">+ <div className="flex min-w-0 items-center gap-3">+ <img src="/brand/nanobot_icon_192.png" alt="" className="h-9 w-9" />+ <div><h1 className="text-base font-semibold">Component gallery · 组件图鉴</h1>+ <p className="text-xs text-muted-foreground">Try components and their states · 查看效果与交互状态</p></div>+ </div>+ <div className="flex flex-wrap items-center gap-4">+ <label className="flex items-center gap-2 text-xs"><span>Dark mode</span>+ <ToggleButton checked={theme === "dark"} onChange={(dark) => setTheme(dark ? "dark" : "light")} label="Dark mode" /></label>+ <LanguageSwitcher />+ </div>+ </header>+ <div className="gallery-workspace">+ <aside className="gallery-sidebar" aria-label="Component navigation">+ <SegmentedControl value={view} ariaLabel="Inventory view" className="mb-4 w-full"+ options={[{ value: "previews", label: "Previews · 预览" }, { value: "all", label: "All source · 源码" }]}+ onChange={(next) => {+ setView(next);+ setGroup("All");+ if (next === "previews" && !examplesByPath.has(selected)) {+ const first = inventory.find((item) => examplesByPath.has(item.path));+ if (first) window.location.hash = new URLSearchParams({ component: first.path }).toString();+ }+ }} />+ <SearchInput type="search" aria-label="Search components" placeholder="Search name, path / 搜索组件" value={query} onChange={(event) => setQuery(event.target.value)} />+ <label className="mt-3 flex items-center gap-2 text-xs text-muted-foreground">Category+ <select aria-label="Component category" value={group} onChange={(event) => setGroup(event.target.value)}+ className="min-w-0 flex-1 rounded-control border bg-background px-2 py-2 text-foreground">+ {groups.map((item) => <option key={item} value={item}>{item}</option>)}+ </select>+ </label>+ <p className="my-3 text-xs leading-5 text-muted-foreground" role="status">{loading ? "Reading source inventory…"+ : view === "previews" ? `${filtered.length} / ${previewCount} modules with previews · 可预览组件`+ : `${filtered.length} / ${inventory.length} source modules · ${previewCount} with previews`}</p>+ <nav className="gallery-source-list" aria-label="Component sources">+ {filtered.map((item) => <a key={item.path} href={`#${new URLSearchParams({ component: item.path })}`}+ aria-current={current?.path === item.path ? "page" : undefined}+ className={cn("block rounded-control px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring",+ current?.path === item.path ? "bg-sidebar-selected text-foreground" : "text-muted-foreground hover:bg-muted hover:text-foreground")}>+ <span className="flex items-center justify-between gap-2"><span className="truncate">{item.name}</span>+ {view === "all" ? <span className="shrink-0 text-[10px] opacity-70">{examplesByPath.has(item.path) ? "Preview" : "Source only"}</span> : null}</span>+ <span className="block truncate text-[11px] opacity-70">{item.group}</span>+ </a>)}+ {!loading && filtered.length === 0 ? <div className="space-y-3 px-3 py-5 text-sm text-muted-foreground">+ <p>No matching {view === "previews" ? "previews" : "source modules"}.</p>+ {query || group !== "All" ? <Button variant="outline" size="sm" onClick={() => { setQuery(""); setGroup("All"); }}>Clear filters</Button> : null}+ {view === "previews" ? <Button variant="ghost" size="sm" onClick={() => { setView("all"); setGroup("All"); }}>Search all source</Button> : null}+ </div> : null}+ </nav>+ <Button variant="ghost" size="sm" className="mt-3 w-full" disabled={loading} onClick={() => setReload((value) => value + 1)}>Refresh inventory</Button>+ </aside>+ <main className="gallery-main">+ {error ? <div role="alert" className="rounded-control border border-destructive/30 p-4 text-sm text-destructive">{error}</div> : null}+ {current ? <article className="mx-auto max-w-5xl" key={current.path}>+ <p className="mb-2 text-xs text-muted-foreground">{current.group}</p>+ <h2 className="text-2xl font-semibold tracking-tight">{example?.title ?? current.name}</h2>+ <p className="mt-3 break-all font-mono text-xs text-muted-foreground">{current.path}</p>+ {example ? <>+ <p className="mt-5 text-sm leading-6 text-muted-foreground">{example.description}</p>+ <section aria-label="Component preview" className="gallery-preview mt-6"><example.Preview /></section>+ <section className="mt-8 space-y-3"><h3 className="text-sm font-semibold">Usage · 使用方法</h3>+ <p className="text-sm leading-6 text-muted-foreground">{example.options}</p><pre className="gallery-code"><code>{example.code}</code></pre>+ {example.files.length > 1 ? <p className="text-xs leading-5 text-muted-foreground">This example composes: {example.files.map((file) => file.split("/").pop()).join(", ")}</p> : null}+ </section>+ </> : <section className="mt-6 space-y-3 rounded-control border p-4">+ <h3 className="text-sm font-semibold">Source only · 暂无独立预览</h3>+ <p className="text-sm leading-6 text-muted-foreground">This entry indexes a source module. Use Previews to browse working examples. 此条目收录源码;切换到“预览”查看可操作示例。</p>+ {relatedExamples.length > 0 ? <div className="space-y-2">+ <p className="text-xs text-muted-foreground">Related component previews · 相关组件预览</p>+ <ul className="space-y-2">{relatedExamples.map((item) => <li key={item.files[0]}>+ <a className="text-sm underline underline-offset-4" href={`#${new URLSearchParams({ component: item.files[0] })}`}>{item.title}</a>+ </li>)}</ul>+ </div> : null}+ </section>}+ <section className="mt-8 space-y-3"><h3 className="text-sm font-semibold">Exports · 导出</h3>+ <p className="break-words font-mono text-xs leading-6 text-muted-foreground">{current.exports.join(", ") || "Internal module"}</p>+ </section>+ <section className="mt-8 space-y-3"><h3 className="text-sm font-semibold">Direct references · 使用位置</h3>+ <p className="text-xs leading-5 text-muted-foreground">Imports and re-exports in product source; tests and this gallery are excluded. Plugin registration may also load modules indirectly.</p>+ {current.usedBy.length ? <ul className="space-y-2">{current.usedBy.map((file) => <li key={file} className="break-all font-mono text-xs text-muted-foreground">{file}</li>)}</ul>+ : <p className="text-sm text-muted-foreground">No direct source references found.</p>}+ </section>+ <details className="mt-8 rounded-control border p-4"><summary className="cursor-pointer text-sm font-semibold">Source code · 源码</summary>+ <pre className="gallery-code mt-4 max-h-[32rem]"><code>{current.source}</code></pre></details>+ </article> : !error ? <p className="text-sm text-muted-foreground">{loading ? "Loading components…" : "No component source files found."}</p> : null}+ </main>+ </div>+ </div>+ </ThemeProvider>;+}diff --git a/webui/src/dev/gallery/channel-fixtures.ts b/webui/src/dev/gallery/channel-fixtures.tsnew file mode 100644index 000000000..75085c9d7--- /dev/null+++ b/webui/src/dev/gallery/channel-fixtures.ts@@ -0,0 +1,23 @@+// Generated by generate_channel_fixtures.py from channel setup contracts.+import type { NanobotFeatureInfo } from "@/lib/types";++export const channelFeatures: Record<string, NanobotFeatureInfo> = {+ "dingtalk": {"name": "dingtalk","display_name": "DingTalk","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.dingtalk.clientId","field": "clientId","kind": "string","choices": [],"required": true},{"key": "channels.dingtalk.clientSecret","field": "clientSecret","kind": "secret","choices": [],"required": true},{"key": "channels.dingtalk.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.dingtalk.allowRemoteMediaRedirects","field": "allowRemoteMediaRedirects","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.dingtalk.remoteMediaRedirectAllowedHosts","field": "remoteMediaRedirectAllowedHosts","kind": "list","choices": [],"required": false},{"key": "channels.dingtalk.groupUserIsolation","field": "groupUserIsolation","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.dingtalk.disablePrivateChat","field": "disablePrivateChat","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.dingtalk.clientId"]]},{"alternatives": [["channels.dingtalk.clientSecret"]]}],"official_url": "https://open.dingtalk.com/"}},+ "discord": {"name": "discord","display_name": "Discord","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.discord.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.discord.proxy","field": "proxy","kind": "string","choices": [],"required": false},{"key": "channels.discord.proxyUsername","field": "proxyUsername","kind": "string","choices": [],"required": false},{"key": "channels.discord.proxyPassword","field": "proxyPassword","kind": "secret","choices": [],"required": false},{"key": "channels.discord.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.discord.allowChannels","field": "allowChannels","kind": "list","choices": [],"required": false},{"key": "channels.discord.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.discord.intents","field": "intents","kind": "int","choices": [],"required": false,"default_value": "37377"},{"key": "channels.discord.readReceiptEmoji","field": "readReceiptEmoji","kind": "string","choices": [],"required": false,"default_value": "👀"},{"key": "channels.discord.workingEmoji","field": "workingEmoji","kind": "string","choices": [],"required": false,"default_value": "🔧"},{"key": "channels.discord.workingEmojiDelay","field": "workingEmojiDelay","kind": "float","choices": [],"required": false,"default_value": "2.0"},{"key": "channels.discord.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.discord.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"}],"requirements": [{"alternatives": [["channels.discord.token"]]}],"official_url": "https://discord.com/developers/applications","verifies_connection": true}},+ "email": {"name": "email","display_name": "Email","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.email.consentGranted","field": "consentGranted","kind": "bool","choices": [],"required": true,"default_value": "false"},{"key": "channels.email.imapHost","field": "imapHost","kind": "string","choices": [],"required": true},{"key": "channels.email.imapPort","field": "imapPort","kind": "int","choices": [],"required": false,"default_value": "993"},{"key": "channels.email.imapUsername","field": "imapUsername","kind": "string","choices": [],"required": true},{"key": "channels.email.imapPassword","field": "imapPassword","kind": "secret","choices": [],"required": true},{"key": "channels.email.smtpHost","field": "smtpHost","kind": "string","choices": [],"required": true},{"key": "channels.email.smtpPort","field": "smtpPort","kind": "int","choices": [],"required": false,"default_value": "587"},{"key": "channels.email.smtpUsername","field": "smtpUsername","kind": "string","choices": [],"required": true},{"key": "channels.email.smtpPassword","field": "smtpPassword","kind": "secret","choices": [],"required": true},{"key": "channels.email.fromAddress","field": "fromAddress","kind": "string","choices": [],"required": false},{"key": "channels.email.pollIntervalSeconds","field": "pollIntervalSeconds","kind": "int","choices": [],"required": false,"default_value": "30"},{"key": "channels.email.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.email.verifyDkim","field": "verifyDkim","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.verifySpf","field": "verifySpf","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.imapMailbox","field": "imapMailbox","kind": "string","choices": [],"required": false,"default_value": "INBOX"},{"key": "channels.email.imapUseSsl","field": "imapUseSsl","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.smtpUseTls","field": "smtpUseTls","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.smtpUseSsl","field": "smtpUseSsl","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.email.autoReplyEnabled","field": "autoReplyEnabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.markSeen","field": "markSeen","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.postAction","field": "postAction","kind": "enum","choices": ["delete","move"],"required": false},{"key": "channels.email.postActionMoveMailbox","field": "postActionMoveMailbox","kind": "string","choices": [],"required": false},{"key": "channels.email.postActionExpunge","field": "postActionExpunge","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.email.postActionIgnoreSkipped","field": "postActionIgnoreSkipped","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.email.maxBodyChars","field": "maxBodyChars","kind": "int","choices": [],"required": false,"default_value": "12000"},{"key": "channels.email.subjectPrefix","field": "subjectPrefix","kind": "string","choices": [],"required": false,"default_value": "Re: "},{"key": "channels.email.allowedAttachmentTypes","field": "allowedAttachmentTypes","kind": "list","choices": [],"required": false},{"key": "channels.email.maxAttachmentSize","field": "maxAttachmentSize","kind": "int","choices": [],"required": false,"default_value": "2000000"},{"key": "channels.email.maxAttachmentsPerEmail","field": "maxAttachmentsPerEmail","kind": "int","choices": [],"required": false,"default_value": "5"},{"key": "channels.email.trustedAuthservIds","field": "trustedAuthservIds","kind": "list","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.email.consentGranted"]]},{"alternatives": [["channels.email.imapHost"]]},{"alternatives": [["channels.email.imapUsername"]]},{"alternatives": [["channels.email.imapPassword"]]},{"alternatives": [["channels.email.smtpHost"]]},{"alternatives": [["channels.email.smtpUsername"]]},{"alternatives": [["channels.email.smtpPassword"]]}],"official_url": "https://support.google.com/accounts/answer/185833","verifies_connection": true}},+ "feishu": {"name": "feishu","display_name": "Feishu","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.feishu.appId","field": "appId","kind": "string","choices": [],"required": true},{"key": "channels.feishu.appSecret","field": "appSecret","kind": "secret","choices": [],"required": true},{"key": "channels.feishu.domain","field": "domain","kind": "enum","choices": ["feishu","lark"],"required": false,"default_value": "feishu"},{"key": "channels.feishu.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.feishu.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.feishu.topicIsolation","field": "topicIsolation","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.feishu.name","field": "name","kind": "string","choices": [],"required": false,"default_value": "nanobot"},{"key": "channels.feishu.encryptKey","field": "encryptKey","kind": "secret","choices": [],"required": false},{"key": "channels.feishu.verificationToken","field": "verificationToken","kind": "secret","choices": [],"required": false},{"key": "channels.feishu.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "THUMBSUP"},{"key": "channels.feishu.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false},{"key": "channels.feishu.toolHintPrefix","field": "toolHintPrefix","kind": "string","choices": [],"required": false,"default_value": "🔧"},{"key": "channels.feishu.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.feishu.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"}],"requirements": [{"alternatives": [["channels.feishu.appId"]]},{"alternatives": [["channels.feishu.appSecret"]]}],"official_url": "https://open.feishu.cn/app"}},+ "linear": {"name": "linear","display_name": "Linear","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.linear.clientId","field": "clientId","kind": "string","choices": [],"required": true},{"key": "channels.linear.clientSecret","field": "clientSecret","kind": "secret","choices": [],"required": true},{"key": "channels.linear.webhookSigningSecret","field": "webhookSigningSecret","kind": "secret","choices": [],"required": true},{"key": "channels.linear.publicBaseUrl","field": "publicBaseUrl","kind": "string","choices": [],"required": true},{"key": "channels.linear.host","field": "host","kind": "string","choices": [],"required": false,"default_value": "0.0.0.0"},{"key": "channels.linear.port","field": "port","kind": "int","choices": [],"required": false,"default_value": "3979"},{"key": "channels.linear.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/linear/webhook"},{"key": "channels.linear.oauthCallbackPath","field": "oauthCallbackPath","kind": "string","choices": [],"required": false,"default_value": "/linear/oauth/callback"},{"key": "channels.linear.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.linear.showReasoning","field": "showReasoning","kind": "bool","choices": [],"required": false,"default_value": "true"}],"requirements": [{"alternatives": [["channels.linear.clientId"]]},{"alternatives": [["channels.linear.clientSecret"]]},{"alternatives": [["channels.linear.webhookSigningSecret"]]},{"alternatives": [["channels.linear.publicBaseUrl"]]}],"official_url": "https://linear.app/settings/api/applications/new"}},+ "matrix": {"name": "matrix","display_name": "Matrix","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.matrix.homeserver","field": "homeserver","kind": "string","choices": [],"required": true,"default_value": "https://matrix.org"},{"key": "channels.matrix.userId","field": "userId","kind": "string","choices": [],"required": true},{"key": "channels.matrix.password","field": "password","kind": "secret","choices": [],"required": false},{"key": "channels.matrix.accessToken","field": "accessToken","kind": "secret","choices": [],"required": false},{"key": "channels.matrix.deviceId","field": "deviceId","kind": "string","choices": [],"required": false},{"key": "channels.matrix.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "open"},{"key": "channels.matrix.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.matrix.e2eeEnabled","field": "e2eeEnabled","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.sasVerification","field": "sasVerification","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.syncStopGraceSeconds","field": "syncStopGraceSeconds","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.matrix.maxMediaBytes","field": "maxMediaBytes","kind": "int","choices": [],"required": false,"default_value": "20971520"},{"key": "channels.matrix.maxConcurrentMediaDownloads","field": "maxConcurrentMediaDownloads","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.matrix.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.matrix.allowRoomMentions","field": "allowRoomMentions","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.matrix.proxy","field": "proxy","kind": "string","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.matrix.homeserver"]]},{"alternatives": [["channels.matrix.userId"]]},{"alternatives": [["channels.matrix.password"],["channels.matrix.accessToken","channels.matrix.deviceId"]]}],"official_url": "https://matrix.org/ecosystem/clients/"}},+ "mattermost": {"name": "mattermost","display_name": "Mattermost","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.mattermost.serverUrl","field": "serverUrl","kind": "string","choices": [],"required": true},{"key": "channels.mattermost.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.mattermost.teamId","field": "teamId","kind": "string","choices": [],"required": false},{"key": "channels.mattermost.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.mattermost.groupPolicyInThread","field": "groupPolicyInThread","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.mattermost.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.mattermost.allowFromMatchMode","field": "allowFromMatchMode","kind": "enum","choices": ["email","id","username"],"required": false,"default_value": "id"},{"key": "channels.mattermost.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.mattermost.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.includeThreadContext","field": "includeThreadContext","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.threadContextLimit","field": "threadContextLimit","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.mattermost.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "eyes"},{"key": "channels.mattermost.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false,"default_value": "white_check_mark"},{"key": "channels.mattermost.sendProgress","field": "sendProgress","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.sendToolHints","field": "sendToolHints","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.mattermost.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "open"},{"key": "channels.mattermost.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.mattermost.serverUrl"]]},{"alternatives": [["channels.mattermost.token"]]}],"official_url": "https://developers.mattermost.com/integrate/reference/bot-accounts/"}},+ "mochat": {"name": "mochat","display_name": "MoChat","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.mochat.baseUrl","field": "baseUrl","kind": "string","choices": [],"required": false,"default_value": "https://mochat.io"},{"key": "channels.mochat.clawToken","field": "clawToken","kind": "secret","choices": [],"required": true},{"key": "channels.mochat.agentUserId","field": "agentUserId","kind": "string","choices": [],"required": false},{"key": "channels.mochat.sessions","field": "sessions","kind": "list","choices": [],"required": false},{"key": "channels.mochat.panels","field": "panels","kind": "list","choices": [],"required": false},{"key": "channels.mochat.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.mochat.socketUrl","field": "socketUrl","kind": "string","choices": [],"required": false},{"key": "channels.mochat.socketPath","field": "socketPath","kind": "string","choices": [],"required": false,"default_value": "/socket.io"},{"key": "channels.mochat.socketDisableMsgpack","field": "socketDisableMsgpack","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.mochat.socketReconnectDelayMs","field": "socketReconnectDelayMs","kind": "int","choices": [],"required": false,"default_value": "1000"},{"key": "channels.mochat.socketMaxReconnectDelayMs","field": "socketMaxReconnectDelayMs","kind": "int","choices": [],"required": false,"default_value": "10000"},{"key": "channels.mochat.socketConnectTimeoutMs","field": "socketConnectTimeoutMs","kind": "int","choices": [],"required": false,"default_value": "10000"},{"key": "channels.mochat.refreshIntervalMs","field": "refreshIntervalMs","kind": "int","choices": [],"required": false,"default_value": "30000"},{"key": "channels.mochat.watchTimeoutMs","field": "watchTimeoutMs","kind": "int","choices": [],"required": false,"default_value": "25000"},{"key": "channels.mochat.watchLimit","field": "watchLimit","kind": "int","choices": [],"required": false,"default_value": "100"},{"key": "channels.mochat.retryDelayMs","field": "retryDelayMs","kind": "int","choices": [],"required": false,"default_value": "500"},{"key": "channels.mochat.maxRetryAttempts","field": "maxRetryAttempts","kind": "int","choices": [],"required": false,"default_value": "0"},{"key": "channels.mochat.mention.requireInGroups","field": "mention.requireInGroups","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.mochat.groups","field": "groups","kind": "json","choices": [],"required": false,"default_value": "{}"},{"key": "channels.mochat.replyDelayMode","field": "replyDelayMode","kind": "string","choices": [],"required": false,"default_value": "non-mention"},{"key": "channels.mochat.replyDelayMs","field": "replyDelayMs","kind": "int","choices": [],"required": false,"default_value": "120000"}],"requirements": [{"alternatives": [["channels.mochat.clawToken"]]}],"official_url": "https://mochat.io/"}},+ "msteams": {"name": "msteams","display_name": "Microsoft Teams","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.msteams.appId","field": "appId","kind": "string","choices": [],"required": true},{"key": "channels.msteams.appPassword","field": "appPassword","kind": "secret","choices": [],"required": true},{"key": "channels.msteams.tenantId","field": "tenantId","kind": "string","choices": [],"required": false},{"key": "channels.msteams.path","field": "path","kind": "string","choices": [],"required": false,"default_value": "/api/messages"},{"key": "channels.msteams.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.msteams.host","field": "host","kind": "string","choices": [],"required": false,"default_value": "0.0.0.0"},{"key": "channels.msteams.port","field": "port","kind": "int","choices": [],"required": false,"default_value": "3978"},{"key": "channels.msteams.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.mentionOnlyResponse","field": "mentionOnlyResponse","kind": "string","choices": [],"required": false,"default_value": "Hi — what can I help with?"},{"key": "channels.msteams.validateInboundAuth","field": "validateInboundAuth","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.refTtlDays","field": "refTtlDays","kind": "int","choices": [],"required": false,"default_value": "30"},{"key": "channels.msteams.pruneWebChatRefs","field": "pruneWebChatRefs","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.pruneNonPersonalRefs","field": "pruneNonPersonalRefs","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.msteams.refTouchIntervalS","field": "refTouchIntervalS","kind": "int","choices": [],"required": false,"default_value": "300"},{"key": "channels.msteams.trustedServiceUrlHosts","field": "trustedServiceUrlHosts","kind": "list","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.msteams.appId"]]},{"alternatives": [["channels.msteams.appPassword"]]}],"official_url": "https://dev.teams.microsoft.com/apps"}},+ "napcat": {"name": "napcat","display_name": "NapCat","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.napcat.wsUrl","field": "wsUrl","kind": "string","choices": [],"required": true,"default_value": "ws://127.0.0.1:3001"},{"key": "channels.napcat.accessToken","field": "accessToken","kind": "secret","choices": [],"required": false},{"key": "channels.napcat.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.napcat.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "mention"},{"key": "channels.napcat.groupPolicyOverrides","field": "groupPolicyOverrides","kind": "json","choices": [],"required": false,"default_value": "{}"},{"key": "channels.napcat.welcomeNewMembers","field": "welcomeNewMembers","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.napcat.maxImageBytes","field": "maxImageBytes","kind": "int","choices": [],"required": false,"default_value": "20971520"}],"requirements": [{"alternatives": [["channels.napcat.wsUrl"]]}],"official_url": "https://napneko.github.io/"}},+ "qq": {"name": "qq","display_name": "QQ","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.qq.appId","field": "appId","kind": "string","choices": [],"required": true},{"key": "channels.qq.secret","field": "secret","kind": "secret","choices": [],"required": true},{"key": "channels.qq.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.qq.msgFormat","field": "msgFormat","kind": "enum","choices": ["markdown","plain"],"required": false,"default_value": "plain"},{"key": "channels.qq.ackMessage","field": "ackMessage","kind": "string","choices": [],"required": false,"default_value": "⏳ Processing..."},{"key": "channels.qq.showCompactionNotices","field": "showCompactionNotices","kind": "bool","choices": [],"required": false,"inheritable": true},{"key": "channels.qq.mediaDir","field": "mediaDir","kind": "string","choices": [],"required": false},{"key": "channels.qq.downloadChunkSize","field": "downloadChunkSize","kind": "int","choices": [],"required": false,"default_value": "262144"},{"key": "channels.qq.downloadMaxBytes","field": "downloadMaxBytes","kind": "int","choices": [],"required": false,"default_value": "209715200"}],"requirements": [{"alternatives": [["channels.qq.appId"]]},{"alternatives": [["channels.qq.secret"]]}],"official_url": "https://q.qq.com/"}},+ "signal": {"name": "signal","display_name": "Signal","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.signal.phoneNumber","field": "phoneNumber","kind": "string","choices": [],"required": true},{"key": "channels.signal.daemonHost","field": "daemonHost","kind": "string","choices": [],"required": false,"default_value": "localhost"},{"key": "channels.signal.daemonPort","field": "daemonPort","kind": "int","choices": [],"required": false,"default_value": "8080"},{"key": "channels.signal.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.signal.group.allowFrom","field": "group.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.signal.groupMessageBufferSize","field": "groupMessageBufferSize","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.signal.attachmentsDir","field": "attachmentsDir","kind": "string","choices": [],"required": false},{"key": "channels.signal.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.signal.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "allowlist"},{"key": "channels.signal.group.enabled","field": "group.enabled","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.signal.group.policy","field": "group.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "allowlist"},{"key": "channels.signal.group.requireMention","field": "group.requireMention","kind": "bool","choices": [],"required": false,"default_value": "true"}],"requirements": [{"alternatives": [["channels.signal.phoneNumber"]]}],"official_url": "https://github.com/bbernhard/signal-cli-rest-api"}},+ "slack": {"name": "slack","display_name": "Slack","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.slack.appToken","field": "appToken","kind": "secret","choices": [],"required": true},{"key": "channels.slack.botToken","field": "botToken","kind": "secret","choices": [],"required": true},{"key": "channels.slack.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.slack.mode","field": "mode","kind": "enum","choices": ["socket"],"required": false,"default_value": "socket"},{"key": "channels.slack.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/slack/events"},{"key": "channels.slack.replyInThread","field": "replyInThread","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "eyes"},{"key": "channels.slack.doneEmoji","field": "doneEmoji","kind": "string","choices": [],"required": false,"default_value": "white_check_mark"},{"key": "channels.slack.includeThreadContext","field": "includeThreadContext","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.threadContextLimit","field": "threadContextLimit","kind": "int","choices": [],"required": false,"default_value": "20"},{"key": "channels.slack.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.groupAllowFrom","field": "groupAllowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.groupRequireMention","field": "groupRequireMention","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.slack.dm.enabled","field": "dm.enabled","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.slack.dm.policy","field": "dm.policy","kind": "enum","choices": ["allowlist","open"],"required": false,"default_value": "open"},{"key": "channels.slack.dm.allowFrom","field": "dm.allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.slack.proxy","field": "proxy","kind": "string","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.slack.appToken"]]},{"alternatives": [["channels.slack.botToken"]]}],"official_url": "https://api.slack.com/apps","verifies_connection": true}},+ "telegram": {"name": "telegram","display_name": "Telegram","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.telegram.token","field": "token","kind": "secret","choices": [],"required": true},{"key": "channels.telegram.proxy","field": "proxy","kind": "string","choices": [],"required": false},{"key": "channels.telegram.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.telegram.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["allowlist","mention","open"],"required": false,"default_value": "mention"},{"key": "channels.telegram.mode","field": "mode","kind": "enum","choices": ["polling","webhook"],"required": false,"default_value": "polling"},{"key": "channels.telegram.replyToMessage","field": "replyToMessage","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.reactEmoji","field": "reactEmoji","kind": "string","choices": [],"required": false,"default_value": "👀"},{"key": "channels.telegram.connectionPoolSize","field": "connectionPoolSize","kind": "int","choices": [],"required": false,"default_value": "32"},{"key": "channels.telegram.poolTimeout","field": "poolTimeout","kind": "float","choices": [],"required": false,"default_value": "5.0"},{"key": "channels.telegram.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.telegram.inlineKeyboards","field": "inlineKeyboards","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.richMessages","field": "richMessages","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.telegram.streamEditInterval","field": "streamEditInterval","kind": "float","choices": [],"required": false,"default_value": "0.6"},{"key": "channels.telegram.webhookUrl","field": "webhookUrl","kind": "string","choices": [],"required": false},{"key": "channels.telegram.webhookListenHost","field": "webhookListenHost","kind": "string","choices": [],"required": false,"default_value": "127.0.0.1"},{"key": "channels.telegram.webhookListenPort","field": "webhookListenPort","kind": "int","choices": [],"required": false,"default_value": "8081"},{"key": "channels.telegram.webhookPath","field": "webhookPath","kind": "string","choices": [],"required": false,"default_value": "/telegram"},{"key": "channels.telegram.webhookSecretToken","field": "webhookSecretToken","kind": "secret","choices": [],"required": false},{"key": "channels.telegram.webhookMaxConnections","field": "webhookMaxConnections","kind": "int","choices": [],"required": false,"default_value": "4"}],"requirements": [{"alternatives": [["channels.telegram.token"]]}],"official_url": "https://t.me/BotFather","verifies_connection": true}},+ "websocket": {"name": "websocket","display_name": "WebSocket","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [],"requirements": [],"official_url": "http://127.0.0.1:8765"}},+ "wecom": {"name": "wecom","display_name": "WeCom","webui": "webui/index.ts","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.wecom.botId","field": "botId","kind": "string","choices": [],"required": true},{"key": "channels.wecom.secret","field": "secret","kind": "secret","choices": [],"required": true},{"key": "channels.wecom.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.wecom.welcomeMessage","field": "welcomeMessage","kind": "string","choices": [],"required": false}],"requirements": [{"alternatives": [["channels.wecom.botId"]]},{"alternatives": [["channels.wecom.secret"]]}],"official_url": "https://developer.work.weixin.qq.com/"}},+ "weixin": {"name": "weixin","display_name": "WeChat","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.weixin.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.weixin.baseUrl","field": "baseUrl","kind": "string","choices": [],"required": false,"default_value": "https://ilinkai.weixin.qq.com"},{"key": "channels.weixin.cdnBaseUrl","field": "cdnBaseUrl","kind": "string","choices": [],"required": false,"default_value": "https://novac2c.cdn.weixin.qq.com/c2c"},{"key": "channels.weixin.routeTag","field": "routeTag","kind": "string","choices": [],"required": false},{"key": "channels.weixin.stateDir","field": "stateDir","kind": "string","choices": [],"required": false},{"key": "channels.weixin.pollTimeout","field": "pollTimeout","kind": "int","choices": [],"required": false,"default_value": "35"},{"key": "channels.weixin.sendProgress","field": "sendProgress","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.sendToolHints","field": "sendToolHints","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.replyProgressMessages","field": "replyProgressMessages","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.replyProgressMaxMessages","field": "replyProgressMaxMessages","kind": "int","choices": [],"required": false,"default_value": "2"},{"key": "channels.weixin.contextMessageBudget","field": "contextMessageBudget","kind": "int","choices": [],"required": false,"default_value": "8"},{"key": "channels.weixin.streaming","field": "streaming","kind": "bool","choices": [],"required": false,"default_value": "true"},{"key": "channels.weixin.blockStreaming","field": "blockStreaming","kind": "bool","choices": [],"required": false,"default_value": "false"},{"key": "channels.weixin.blockStreamingMinChars","field": "blockStreamingMinChars","kind": "int","choices": [],"required": false,"default_value": "1200"},{"key": "channels.weixin.blockStreamingMaxMessages","field": "blockStreamingMaxMessages","kind": "int","choices": [],"required": false,"default_value": "3"}],"requirements": [{"alternatives": [["channels.weixin.token"]]}],"official_url": "https://weixin.qq.com/"}},+ "whatsapp": {"name": "whatsapp","display_name": "WhatsApp","webui": "webui/index.tsx","type": "channel","enabled": false,"installed": true,"configured": false,"ready": false,"status": "not_enabled","install_supported": true,"requires_restart": false,"runtime_status": "stopped","config_values": {},"configured_fields": [],"setup": {"fields": [{"key": "channels.whatsapp.proxy","field": "proxy","kind": "string","choices": [],"required": false},{"key": "channels.whatsapp.allowFrom","field": "allowFrom","kind": "list","choices": [],"required": false},{"key": "channels.whatsapp.groupPolicy","field": "groupPolicy","kind": "enum","choices": ["mention","open"],"required": false,"default_value": "open"}],"requirements": [],"official_url": "https://faq.whatsapp.com/"}},+};diff --git a/webui/src/dev/gallery/channels-feishu-whatsapp.tsx b/webui/src/dev/gallery/channels-feishu-whatsapp.tsxnew file mode 100644index 000000000..1c6425b0a--- /dev/null+++ b/webui/src/dev/gallery/channels-feishu-whatsapp.tsx@@ -0,0 +1,154 @@+import { useState } from "react";++import { FeishuAssistantsPanelView, type FeishuConnectOptions } from "../../../../nanobot/channels/feishu/webui/FeishuAssistantsPanelView";+import { FeishuConnectFlowView } from "../../../../nanobot/channels/feishu/webui/FeishuConnectFlowView";+import { WhatsAppConnectFlowView } from "../../../../nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView";+import type { ChannelConnectPayload, NanobotChannelInstanceInfo } from "@/lib/types";+import { channelFeatures } from "./channel-fixtures";+import { StatePicker, type ComponentExample } from "./example";++const connectStates = ["idle", "starting", "pending", "succeeded", "expired", "failed", "cancelled", "error"] as const;+type ConnectState = typeof connectStates[number];++function connectSnapshot(state: ConnectState): ChannelConnectPayload | null {+ if (state === "idle" || state === "starting" || state === "error") return null;+ return {+ session_id: "gallery-authorization",+ status: state,+ qr_url: "https://example.invalid/channel-authorization",+ };+}++function ConnectPreview({ channel }: { channel: "feishu" | "whatsapp" }) {+ const [state, setState] = useState<ConnectState>("pending");+ const connect = connectSnapshot(state);+ const props = {+ connect,+ busy: state === "starting",+ error: state === "error" ? "Authorization is temporarily unavailable. Try again." : null,+ onStart: () => setState("pending"),+ onCancel: () => setState("cancelled"),+ onPoll: async () => connect,+ };+ return <>+ <StatePicker label={`${channel === "feishu" ? "Feishu" : "WhatsApp"} 连接状态`} value={state} options={connectStates} onChange={setState} />+ {channel === "feishu"+ ? <FeishuConnectFlowView {...props} autoStart={state === "starting"} />+ : <WhatsAppConnectFlowView {...props} />}+ </>;+}++function FeishuConnectionPreview() {+ return <ConnectPreview channel="feishu" />;+}++function WhatsAppConnectionPreview() {+ return <ConnectPreview channel="whatsapp" />;+}++const assistantStates = ["running", "starting", "failed", "needs-authorization", "mixed"] as const;+type AssistantState = typeof assistantStates[number];++function assistantSnapshots(state: AssistantState): NanobotChannelInstanceInfo[] {+ const configured = state !== "needs-authorization";+ const first: NanobotChannelInstanceInfo = {+ id: "default",+ name: "nanobot",+ display_name: "Support assistant",+ enabled: configured,+ configured,+ runtime_status: state === "mixed" ? "running" : state === "needs-authorization" ? "stopped" : state,+ config_values: { ...channelFeatures.feishu.config_values, "channels.feishu.appId": "cli_gallery", "channels.feishu.domain": "feishu" },+ configured_fields: configured ? ["channels.feishu.appId", "channels.feishu.appSecret"] : [],+ };+ return state === "mixed" ? [first, {+ ...first,+ id: "product",+ display_name: "Product assistant",+ enabled: false,+ configured: false,+ runtime_status: "stopped",+ configured_fields: [],+ }] : [first];+}++function AssistantAuthorizationPreview({ idleLabel }: FeishuConnectOptions) {+ const [state, setState] = useState<ConnectState>("idle");+ const connect = connectSnapshot(state);+ return <FeishuConnectFlowView+ idleLabel={idleLabel}+ connect={connect}+ busy={false}+ error={null}+ onStart={() => setState("pending")}+ onCancel={() => setState("cancelled")}+ onPoll={async () => connect}+ />;+}++function FeishuAssistantsPreview() {+ const [state, setState] = useState<AssistantState>("mixed");+ const [instances, setInstances] = useState(() => assistantSnapshots("mixed"));+ const [action, setAction] = useState("");+ const feature = {+ ...channelFeatures.feishu,+ enabled: instances.some((instance) => instance.enabled),+ configured: instances.some((instance) => instance.configured),+ instances,+ runtime_error: state === "failed" ? "The assistant stopped. Check its credentials before restarting." : undefined,+ };+ return <>+ <StatePicker label="助手运行状态" value={state} options={assistantStates} onChange={(next) => {+ setState(next);+ setInstances(assistantSnapshots(next));+ setAction("");+ }} />+ <FeishuAssistantsPanelView+ key={state}+ feature={feature}+ showBrandLogos={false}+ onToggleInstance={(instance, enabled) => {+ setInstances((current) => current.map((item) => item.id === instance.id ? {+ ...item, enabled, runtime_status: enabled ? "running" : "stopped",+ } : item));+ setAction(`${instance.display_name}: ${enabled ? "On" : "Off"}`);+ }}+ onSaveInstance={(instance, values) => {+ setInstances((current) => current.map((item) => item.id === instance.id ? {+ ...item, config_values: { ...item.config_values, ...values },+ configured_fields: [...new Set([...item.configured_fields, ...Object.keys(values)])],+ } : item));+ setAction(`${instance.display_name}: saved ${Object.keys(values).length} preview fields`);+ }}+ renderConnectFlow={(options) => <AssistantAuthorizationPreview {...options} />}+ />+ {action ? <p role="status" className="mt-4 text-xs text-muted-foreground">{action}</p> : null}+ </>;+}++export const feishuWhatsAppChannelExamples: ComponentExample[] = [+ {+ title: "FeishuConnectFlowView · 飞书扫码授权",+ files: ["nanobot/channels/feishu/webui/FeishuConnectFlowView.tsx", "webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx"],+ description: "查看飞书真实扫码界面,切换等待、授权成功、到期、取消与错误,体验取消和重新扫码。",+ options: "connect、busy 和 error 是已有显示状态;视图本地生成二维码。开始、取消与轮询由功能入口提供,预览回调只改变当前示例。",+ code: "<FeishuConnectFlowView connect={connect} busy={busy} error={error} onStart={start} onCancel={cancel} onPoll={poll} />",+ Preview: FeishuConnectionPreview,+ },+ {+ title: "FeishuAssistantsPanelView · 飞书助手管理",+ files: ["nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsx", "webui/src/components/settings/channels/ChannelInstancesPanelView.tsx"],+ description: "展示多个真实助手卡片、运行与授权状态,试用开关、高级设置、保存和添加另一个助手。",+ options: "feature 和 instances 提供助手快照;视图管理字段草稿与保存反馈。onToggleInstance、onSaveInstance 与 renderConnectFlow 由所属功能接入运行时操作。",+ code: "<FeishuAssistantsPanelView feature={feature} showBrandLogos={false} onToggleInstance={toggle} onSaveInstance={save} renderConnectFlow={renderAuthorization} />",+ Preview: FeishuAssistantsPreview,+ },+ {+ title: "WhatsAppConnectFlowView · WhatsApp 设备关联",+ files: ["nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsx"],+ description: "使用正式 WhatsApp 极简二维码布局,比较自动连接、关联成功、到期和错误提示,并试用关联另一个账号。",+ options: "此视图沿用自动开始和极简布局的显示规则;调用方控制状态和重试。真实自动开始、强制重试和轮询仍由连接功能入口负责。",+ code: "<WhatsAppConnectFlowView connect={connect} busy={busy} error={error} onStart={start} onCancel={cancel} onPoll={poll} />",+ Preview: WhatsAppConnectionPreview,+ },+];diff --git a/webui/src/dev/gallery/channels-linear.tsx b/webui/src/dev/gallery/channels-linear.tsxnew file mode 100644index 000000000..d73d98252--- /dev/null+++ b/webui/src/dev/gallery/channels-linear.tsx@@ -0,0 +1,196 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { channelSetup } from "@/components/settings/channels/ChannelIdentity";+import { defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";+import type { ChannelConnectPayload, NanobotFeatureInfo } from "@/lib/types";+import { LinearPanelView } from "../../../../nanobot/channels/linear/webui/LinearPanelView";+import { LinearMemberAccessView, type LinearMemberAccessSnapshot } from "../../../../nanobot/channels/linear/webui/LinearMemberAccessView";+import { LinearConnectFlowView, linearConnectLabels } from "../../../../nanobot/channels/linear/webui/LinearConnectFlowView";+import { LinearResetConnectionView } from "../../../../nanobot/channels/linear/webui/LinearResetConnectionView";+import type { LinearInstallationSummary } from "../../../../nanobot/channels/linear/webui/types";+import { channelFeatures } from "./channel-fixtures";+import { StatePicker, type ComponentExample } from "./example";++const workspace: LinearInstallationSummary = {+ organization_id: "gallery-workspace", organization_name: "Nanobot team",+ scopes: ["read", "write", "app:assignable", "app:mentionable"], authorization_status: "authorized",+};++type MemberStory = "members" | "loading" | "refreshing" | "empty" | "error" | "saving" | "save-error" | "allow-all";++function memberSnapshot(story: MemberStory): LinearMemberAccessSnapshot {+ const members = [+ { id: "gallery-alex", name: "Alex", teams: ["Engineering"], allowed: true },+ { id: "gallery-robin", name: "Robin", teams: ["Design"], allowed: false },+ { id: "gallery-alex-two", name: "Alex", teams: ["Support"], allowed: false },+ ];+ return {+ payload: story === "loading" || story === "error" ? null : {+ session_id: "gallery-members", status: "members", organization_id: workspace.organization_id,+ legacy_allow_all: story === "allow-all", members: story === "empty" ? [] : members,+ },+ loading: story === "loading" || story === "refreshing",+ error: story === "error" ? "Member directory is unavailable." : null,+ saves: story === "saving" ? { "gallery-alex": { status: "saving" } }+ : story === "save-error" ? { "gallery-alex": { status: "error", message: "Access was not confirmed." } } : {},+ };+}++function MemberList({ story = "members", disabled = false }: { story?: MemberStory; disabled?: boolean }) {+ const [snapshot, setSnapshot] = useState(() => memberSnapshot(story));+ return <LinearMemberAccessView snapshot={snapshot} disabled={disabled}+ onLoad={(force) => { if (force) setSnapshot(memberSnapshot("members")); }}+ onSetAllowed={(id, allowed) => setSnapshot(current => ({ ...current,+ payload: current.payload ? { ...current.payload,+ members: current.payload.members.map(member => member.id === id ? { ...member, allowed } : member),+ } : null,+ saves: { ...current.saves, [id]: { status: "saved" } },+ }))} />;+}++function MembersPreview() {+ const [story, setStory] = useState<MemberStory>("members");+ return <><StatePicker label="成员状态" value={story}+ options={["members", "loading", "refreshing", "empty", "error", "saving", "save-error", "allow-all"]}+ onChange={setStory} /><div className="overflow-hidden rounded-panel border border-border/70">+ <MemberList key={story} story={story} /></div></>;+}++type ConnectStory = "idle" | "starting" | "pending" | "succeeded" | "cancelled" | "failed";+function connection(story: ConnectStory): ChannelConnectPayload | null {+ if (story === "idle" || story === "starting") return null;+ return { session_id: "gallery-linear-authorization", status: story,+ qr_url: story === "pending" ? "https://linear.app/oauth/authorize?client_id=gallery-example" : undefined,+ };+}++function AuthorizationPreview() {+ const { t } = useTranslation();+ const [story, setStory] = useState<ConnectStory>("idle");+ const connect = connection(story);+ return <><StatePicker label="授权阶段" value={story}+ options={["idle", "starting", "pending", "succeeded", "cancelled", "failed"]} onChange={setStory} />+ <LinearConnectFlowView connect={connect} busy={story === "starting"} error={story === "failed" ? "Authorization could not be completed." : null}+ labels={linearConnectLabels(channelTranslator(t, "linear"))}+ onStart={() => setStory("pending")} onCancel={() => setStory("cancelled")}+ onPoll={async () => connect} />+ <p className="mt-4 text-xs text-muted-foreground">授权链接与工作区为示例数据;开始、取消只更新预览阶段。</p></>;+}++type ResetStory = "success" | "partial-error";+function ResetAction({ story = "success", disabled = false, onComplete }: {+ story?: ResetStory; disabled?: boolean; onComplete?: () => void;+}) {+ const [feedback, setFeedback] = useState("");+ return <><LinearResetConnectionView disabled={disabled} onReset={async () => {+ await new Promise(resolve => window.setTimeout(resolve, 700));+ if (story === "partial-error") throw new Error("The channel could not be stopped. App settings were kept.");+ setFeedback("预览工作区及应用设置已清除。");+ onComplete?.();+ }} /><p role="status" className="mt-3 text-xs text-muted-foreground">{feedback}</p></>;+}++function ResetPreview() {+ const [story, setStory] = useState<ResetStory>("success");+ return <><StatePicker label="重置结果" value={story} options={["success", "partial-error"]} onChange={setStory} />+ <ResetAction key={story} story={story} /></>;+}++type PanelStory = "setup" | "configured" | "connected" | "missing-scopes" | "loading" | "inspection-error" | "save-error" | "runtime-error";+function panelFeature(story: PanelStory): NanobotFeatureInfo {+ const base = channelFeatures.linear;+ if (story === "setup") return base;+ return { ...base, configured: true, enabled: story === "connected" || story === "missing-scopes",+ runtime_status: story === "runtime-error" ? "failed" : story === "connected" || story === "missing-scopes" ? "running" : "stopped",+ runtime_error: story === "runtime-error" ? "Linear webhook could not be started." : undefined,+ configured_fields: ["channels.linear.clientId", "channels.linear.clientSecret", "channels.linear.webhookSigningSecret", "channels.linear.publicBaseUrl"],+ config_values: { ...base.config_values, "channels.linear.clientId": "gallery-linear-app", "channels.linear.publicBaseUrl": "https://nanobot.example" },+ };+}++function PanelComposition({ story }: { story: PanelStory }) {+ const { t, i18n } = useTranslation();+ const [feature, setFeature] = useState(() => panelFeature(story));+ const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language);+ const fields = setup.fields ?? [];+ const advancedFields = setup.manualFields ?? [];+ const [values, setValues] = useState(() => defaultChannelFieldValues([...fields, ...advancedFields], feature.config_values));+ const [configuredFields, setConfiguredFields] = useState(() => new Set(feature.configured_fields ?? []));+ const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});+ const [dirty, setDirty] = useState(false);+ const [saved, setSaved] = useState(false);+ const [notice, setNotice] = useState<string | null>(story === "save-error" ? "Settings could not be saved. Your draft was kept." : null);+ const [workspaceError, setWorkspaceError] = useState<string | null>(null);+ const [loading, setLoading] = useState(story === "loading");+ const [inspectionError, setInspectionError] = useState<string | null>(story === "inspection-error" ? "Connected workspaces could not be inspected." : null);+ const [installations, setInstallations] = useState<LinearInstallationSummary[]>(story === "connected" || story === "missing-scopes"+ ? [story === "missing-scopes" ? { ...workspace, authorization_status: "missing_scopes", missing_scopes: ["app:mentionable"] } : workspace] : []);+ const [connectStory, setConnectStory] = useState<ConnectStory>("idle");+ const [feedback, setFeedback] = useState("");+ const connecting = connectStory === "pending";+ const credentialsSaved = fields.filter(field => !field.optional).every(field =>+ configuredFields.has(field.key) || Boolean(feature.config_values?.[field.key]?.trim()));+ const save = async () => {+ if (story === "save-error") { setNotice("Settings could not be saved. Your draft was kept."); return false; }+ setFeature(current => ({ ...current, config_values: { ...current.config_values, ...values } }));+ setDirty(false); setSaved(true); setNotice(null); return true;+ };+ const connect = connection(connectStory);+ return <><LinearPanelView feature={feature} showBrandLogos={false} fields={fields} advancedFields={advancedFields}+ formProps={{ values, configuredFields, visibleSecrets, compact: true,+ disabled: connecting, onToggleSecret: (key) => setVisibleSecrets(current => ({ ...current, [key]: !current[key] })),+ onChange: (key, value) => { setValues(current => ({ ...current, [key]: value })); setDirty(true); setSaved(false); setNotice(null); },+ onFieldBlur: () => { void save(); },+ }}+ state={{ busy: false, dirty, saving: false, saved, connecting, credentialsSaved, connectionGeneration: 0, notice }}+ workspaces={{ installations: loading || inspectionError ? null : installations,+ logos: {}, loading, inspectionError,+ disconnectingId: null, notice: null, error: workspaceError }}+ onSave={save} onSaveSecret={async (key) => { setConfiguredFields(current => new Set(current).add(key)); setSaved(true); }}+ onRefreshWorkspaces={async () => { setLoading(false); setInspectionError(null); setFeedback("已刷新示例工作区。"); }}+ onDisconnectWorkspace={async (item, onRemoved) => {+ setInstallations(current => current.filter(entry => entry.organization_id !== item.organization_id));+ setFeature(current => ({ ...current, runtime_status: "stopped", enabled: false }));+ onRemoved(); setFeedback(`已移除示例工作区:${item.organization_name}`);+ }} onClearWorkspaceError={() => setWorkspaceError(null)} onRequestConnection={() => setConnectStory("pending")}+ onConfigureMcp={() => setFeedback("已选择 Linear MCP 配置入口。")}+ renderMemberAccess={(organizationId, disabled) => <MemberList key={organizationId} disabled={disabled} />}+ renderResetConnection={({ disabled, onComplete }) => <ResetAction disabled={disabled} onComplete={() => {+ setInstallations([]); setConfiguredFields(new Set()); setFeature(panelFeature("setup"));+ setValues(defaultChannelFieldValues([...fields, ...advancedFields])); onComplete();+ }} />}+ renderConnectFlow={(renderActions) => <LinearConnectFlowView connect={connect} busy={false} error={null}+ labels={linearConnectLabels(channelTranslator(t, "linear"))} connected={feature.runtime_status === "running" && installations.length > 0}+ suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"}+ renderActions={renderActions} onStart={() => setConnectStory("pending")} onCancel={() => setConnectStory("cancelled")}+ onPoll={async () => connect} />} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">{feedback}</p></>;+}++function PanelPreview() {+ const [story, setStory] = useState<PanelStory>("connected");+ return <><StatePicker label="Linear 配置状态" value={story}+ options={["setup", "configured", "connected", "missing-scopes", "loading", "inspection-error", "save-error", "runtime-error"]}+ onChange={setStory} /><PanelComposition key={story} story={story} /></>;+}++export const linearChannelExamples: ComponentExample[] = [+ { title: "LinearPanelView · Linear 配置", files: ["nanobot/channels/linear/webui/LinearPanelView.tsx"], Preview: PanelPreview,+ description: "真实 Linear 配置面板:应用信息、密钥、高级设置、工作区菜单、成员权限及浏览器授权。",+ options: "state 与 workspaces 提供快照;工作区、保存与 MCP 操作由回调接入。三个插槽组合生产所用的成员、授权和重置视图。",+ code: "<LinearPanelView feature={feature} state={state} workspaces={workspaces} formProps={formProps} {...actions} {...composition} />" },+ { title: "LinearMemberAccessView · 成员访问", files: ["nanobot/channels/linear/webui/LinearMemberAccessView.tsx"], Preview: MembersPreview,+ description: "展开成员目录、搜索同名成员、修改权限;比较加载、刷新、空列表、保存和确认失败状态。",+ options: "snapshot 是已确认的成员状态。onLoad 与 onSetAllowed 交给频道入口;权限校验仍由网关负责。",+ code: "<LinearMemberAccessView snapshot={snapshot} onLoad={refresh} onSetAllowed={saveAccess} />" },+ { title: "LinearConnectFlowView · Linear 授权", files: ["nanobot/channels/linear/webui/LinearConnectFlowView.tsx"], Preview: AuthorizationPreview,+ description: "真实浏览器授权入口与等待提示,支持开始、取消、成功与失败阶段。",+ options: "复用 ChannelQrConnectFlowView,Linear 提供浏览器授权展示、标签与焦点处理。会话创建及轮询留在运行时入口。",+ code: "<LinearConnectFlowView connect={authorization} labels={labels} busy={busy} error={error} onStart={start} onCancel={cancel} onPoll={poll} />" },+ { title: "LinearResetConnectionView · 重置连接", files: ["nanobot/channels/linear/webui/LinearResetConnectionView.tsx"], Preview: ResetPreview,+ description: "打开重置确认,查看清除与保留范围、忙碌状态和部分完成后的重试提示。",+ options: "onReset 负责运行完整撤销与清理事务;视图管理确认、错误、关闭限制与焦点恢复。",+ code: "<LinearResetConnectionView disabled={false} onReset={resetConnection} />" },+];diff --git a/webui/src/dev/gallery/channels-weixin.tsx b/webui/src/dev/gallery/channels-weixin.tsxnew file mode 100644index 000000000..f4f7ac8c9--- /dev/null+++ b/webui/src/dev/gallery/channels-weixin.tsx@@ -0,0 +1,110 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";++import { channelTranslator } from "@/channel-plugins/i18n";+import { defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";+import type { ChannelConnectPayload } from "@/lib/types";+import { WeixinPanelView } from "../../../../nanobot/channels/weixin/webui/WeixinPanelView";+import { WeixinConnectFlowView } from "../../../../nanobot/channels/weixin/webui/WeixinConnectFlowView";+import {+ localizeBooleanFields,+ WEIXIN_AUTH_EXPIRED_MESSAGE,+ weixinSetupFields,+ type WeixinVerificationPayload,+} from "../../../../nanobot/channels/weixin/webui/presentation";++import { channelFeatures } from "./channel-fixtures";+import { StatePicker, type ComponentExample } from "./example";++const scan: ChannelConnectPayload = {+ session_id: "gallery-weixin",+ status: "pending",+ qr_url: "https://example.com/gallery/weixin-login",+};++type ConnectState = "starting" | "scan" | "verify" | "verify-error" | "connected"+ | "expired" | "failed" | "cancelled" | "error";++function WeixinConnectPreview() {+ const [mode, setMode] = useState<ConnectState>("scan");+ const [notice, setNotice] = useState("");+ const connect: ChannelConnectPayload | WeixinVerificationPayload | null = mode === "starting" ? null+ : mode === "scan" || mode === "error" ? scan+ : mode === "verify" || mode === "verify-error" ? {+ ...scan, challenge: "verify_code", verification_failed: mode === "verify-error",+ } : { ...scan, status: mode === "connected" ? "succeeded" : mode };++ return <>+ <StatePicker label="微信连接状态" value={mode}+ options={["starting", "scan", "verify", "verify-error", "connected", "expired", "failed", "cancelled", "error"]}+ onChange={setMode} />+ <WeixinConnectFlowView connect={connect} busy={mode === "starting"} autoStart minimalPending+ error={mode === "error" ? "Connection interrupted. Try again." : null}+ onStart={() => { setMode("scan"); setNotice("已显示新的预览二维码。"); }}+ onCancel={() => setMode("cancelled")}+ onPoll={async (params) => {+ if (params?.verify_code === "123456") {+ setMode("connected");+ return { ...scan, status: "succeeded" };+ }+ setMode("verify-error");+ return { ...scan, challenge: "verify_code", verification_failed: true };+ }} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">{notice || "验证码预览输入 123456 可完成连接;其他输入会保留草稿并显示错误。"}</p>+ </>;+}++type PanelState = "unconfigured" | "running" | "auth-expired" | "saving" | "saved" | "save-error";++function WeixinPanelPreview() {+ const { t, i18n } = useTranslation();+ const channelTx = channelTranslator(t, "weixin");+ const [mode, setMode] = useState<PanelState>("running");+ const [edited, setEdited] = useState(false);+ const feature = {+ ...channelFeatures.weixin,+ configured: mode !== "unconfigured",+ enabled: mode !== "unconfigured",+ runtime_status: mode === "auth-expired" ? "failed" : mode === "unconfigured" ? "stopped" : "running",+ runtime_error: mode === "auth-expired" ? WEIXIN_AUTH_EXPIRED_MESSAGE : undefined,+ };+ const setup = weixinSetupFields(feature, i18n.resolvedLanguage ?? i18n.language);+ const onLabel = t("settings.values.on", { defaultValue: "On" });+ const offLabel = t("settings.values.off", { defaultValue: "Off" });+ const primaryFields = localizeBooleanFields(setup.primary, onLabel, offLabel);+ const advancedFields = localizeBooleanFields(setup.advanced, onLabel, offLabel);+ const [values, setValues] = useState(() => defaultChannelFieldValues([...primaryFields, ...advancedFields], {+ "channels.weixin.allowFrom": "preview-user",+ }));+ const [connect, setConnect] = useState<ChannelConnectPayload>(scan);+ const runtimeError = mode === "auth-expired" ? channelTx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE) : undefined;++ return <>+ <StatePicker label="微信面板状态" value={mode}+ options={["unconfigured", "running", "auth-expired", "saving", "saved", "save-error"]}+ onChange={(next) => { setMode(next); setEdited(false); }} />+ <WeixinPanelView feature={feature} actionKey={null} showBrandLogos={false}+ primaryFields={primaryFields} advancedFields={advancedFields} fieldValues={values}+ configuredFields={new Set()} secretVisibilityKey="gallery-weixin" runtimeError={runtimeError}+ saving={mode === "saving" && !edited} saveState={mode === "saved" || edited ? "saved" : "idle"}+ saveError={mode === "save-error" && !edited ? "Unable to save settings. Your draft is preserved." : null}+ connectFlow={mode === "unconfigured" || mode === "auth-expired" ? <WeixinConnectFlowView+ connect={connect} busy={false} error={null} autoStart minimalPending+ suppressSucceeded={mode === "auth-expired"}+ onStart={() => setConnect(scan)} onCancel={() => setConnect({ ...scan, status: "cancelled" })}+ onPoll={async () => connect} /> : null}+ onInstall={() => {}}+ onFieldChange={(key, value) => { setValues((current) => ({ ...current, [key]: value })); setEdited(true); }} />+ </>;+}++export const weixinChannelExamples: ComponentExample[] = [+ { title: "WeixinPanelView · 微信设置", files: ["nanobot/channels/weixin/webui/WeixinPanelView.tsx"],+ Preview: WeixinPanelPreview, description: "查看微信设置、高级参数、保存反馈和登录过期恢复。",+ options: "字段来自频道的真实设置契约。视图管理展开和密钥可见状态;运行时入口负责自动保存、草稿合并和登录恢复。",+ code: '<WeixinPanelView feature={feature} primaryFields={primary} advancedFields={advanced} fieldValues={values} saving={saving} saveState={saveState} saveError={error} connectFlow={connectFlow} onFieldChange={change} />' },+ { title: "WeixinConnectFlowView · 微信扫码与验证", files: ["nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx"],+ Preview: WeixinConnectPreview, description: "比较扫码、验证码、成功、过期、取消和连接错误。",+ options: "视图接收连接快照与操作回调,并保留验证码草稿。二维码生成在浏览器中进行;授权启动、轮询暂停、刷新和取消由真实入口负责。",+ code: '<WeixinConnectFlowView connect={connect} busy={busy} error={error} autoStart minimalPending onStart={start} onCancel={cancel} onPoll={verify} />' },+];diff --git a/webui/src/dev/gallery/channels.tsx b/webui/src/dev/gallery/channels.tsxnew file mode 100644index 000000000..9596668c0--- /dev/null+++ b/webui/src/dev/gallery/channels.tsx@@ -0,0 +1,130 @@+import { useId, useState } from "react";+import { useTranslation } from "react-i18next";++import { registeredChannelUiContributions } from "@/channel-plugins/registry";+import { ChannelSetupSurfaceView } from "@/components/settings/channels/ChannelSetupSurfaceView";+import { channelRequirementErrors, focusFirstChannelFieldError } from "@/components/settings/channels/ChannelCredentialFields";+import { defaultChannelFieldValues } from "@/components/settings/channels/CredentialForm";+import { CHANNEL_SETUP_PANEL_CLASS_NAME, ChannelLogo, channelSetup, localizedChannelDisplayName } from "@/components/settings/channels/ChannelIdentity";+import type { ChannelValidationPayload } from "@/lib/types";+import { copyTextToClipboard } from "@/lib/clipboard";+import { channelFeatures } from "./channel-fixtures";+import { StatePicker, type ComponentExample } from "./example";++function ChannelEntryPreview({ name }: { name: string }) {+ const { t, i18n } = useTranslation();+ const [mode, setMode] = useState<"setup" | "configured" | "enabled" | "checking" | "error">("setup");+ return <><StatePicker label="频道配置状态" value={mode}+ options={["setup", "configured", "enabled", "checking", "error"]} onChange={setMode} />+ <ChannelFormPreview key={mode} name={name} mode={mode} locale={i18n.resolvedLanguage ?? i18n.language} t={t} />+ </>;+}++function ChannelFormPreview({ name, mode, locale, t }: {+ name: string;+ mode: "setup" | "configured" | "enabled" | "checking" | "error";+ locale: string;+ t: ReturnType<typeof useTranslation>["t"];+}) {+ const snapshot = channelFeatures[name];+ const configured = mode !== "setup";+ const [enabled, setEnabled] = useState(mode === "enabled");+ const feature = { ...snapshot, configured, enabled, ready: configured, status: enabled ? "enabled" : "not_enabled",+ configured_fields: configured ? snapshot.setup!.fields.filter((field) => field.kind === "secret").map((field) => field.key) : [],+ runtime_status: enabled ? "running" : "stopped",+ runtime_error: mode === "error" ? "Example credentials were rejected. Update the preview values and retry." : undefined };+ const setup = channelSetup(feature, locale);+ const fields = setup.fields ?? [];+ const requirementKeys = new Set((setup.requirements ?? []).flatMap((item) => item.alternatives.flat()));+ const primaryFields = fields.filter((field) => !field.optional || requirementKeys.has(field.key));+ const advancedFields = fields.filter((field) => !primaryFields.includes(field));+ const configuredFields = new Set(feature.configured_fields);+ const savedSecretFields = fields.filter((field) => field.secret && configuredFields.has(field.key));+ const [values, setValues] = useState(() => {+ const initial = defaultChannelFieldValues(fields, feature.config_values);+ if (configured) for (const field of fields) {+ if (!field.optional && field.kind === "bool") initial[field.key] = "true";+ if (!field.secret && !field.optional && !initial[field.key]?.trim()) {+ initial[field.key] = field.inputType === "url" ? "https://chat.example.com" : `preview-${field.key.split(".").at(-1)}`;+ }+ }+ return initial;+ });+ const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});+ const [clearedSecrets, setClearedSecrets] = useState<Set<string>>(() => new Set());+ const [errors, setErrors] = useState<Record<string, string>>({});+ const [advancedOpen, setAdvancedOpen] = useState(false);+ const [notice, setNotice] = useState<string | null>(null);+ const [saved, setSaved] = useState(false);+ const [checked, setChecked] = useState(false);+ const advancedPanelId = useId();+ const validate = () => {+ const next = channelRequirementErrors(fields, setup.requirements ?? [], values, configuredFields, clearedSecrets,+ t("settings.channels.fieldRequired", { defaultValue: "Required to complete setup." }));+ setErrors(next);+ if (Object.keys(next).length) {+ if (advancedFields.some((field) => next[field.key])) setAdvancedOpen(true);+ focusFirstChannelFieldError(next);+ setNotice(t("settings.channels.validationFailed", { defaultValue: "Check the required setup before enabling." }));+ return false;+ }+ setSaved(true);+ setNotice("预览配置已保存");+ return true;+ };+ const validation: ChannelValidationPayload | null = checked ? {+ name, status: "connected", can_enable: true, requires_restart: false, missing_fields: [],+ checks: [{ id: "preview", label: "Preview configuration", status: "pass" }],+ } : null;+ return <aside className={CHANNEL_SETUP_PANEL_CLASS_NAME}>+ <ChannelSetupSurfaceView feature={feature} setup={setup}+ header={<div className="flex min-w-0 items-center gap-3"><ChannelLogo feature={feature} showBrandLogos={false} />+ <h3 className="sr-only">{localizedChannelDisplayName(feature, t)}</h3></div>}+ primaryFields={primaryFields} advancedFields={advancedFields} savedSecretFields={savedSecretFields}+ availablePresets={configured ? [] : setup.presets ?? []} configuredFields={configuredFields}+ fieldValues={values} visibleSecrets={visibleSecrets} clearedSecrets={clearedSecrets} fieldErrors={errors}+ actionPending={mode === "checking"} enabled={enabled} autoSaving={false} autoSaveState={saved ? "saved" : "idle"}+ advancedOpen={advancedOpen} advancedPanelId={advancedPanelId} validation={validation} validating={mode === "checking"} notice={notice}+ onAdvancedOpenChange={setAdvancedOpen}+ onChangeField={(key, value) => { setValues((current) => ({ ...current, [key]: value })); setErrors({}); setSaved(false); }}+ onFieldBlur={() => { setSaved(true); }}+ onToggleSecret={(key) => setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }))}+ onClearSecret={(key, clear) => setClearedSecrets((current) => {+ const next = new Set(current); if (clear) next.add(key); else next.delete(key); return next;+ })}+ onApplyPreset={(preset) => { setValues((current) => ({ ...current, ...preset.values })); setSaved(false); }}+ onSubmit={() => { if (validate()) setEnabled(true); }}+ onCheckConnection={() => { if (validate()) setChecked(true); }}+ onToggleEnabled={(next) => { if (!next || validate()) setEnabled(next); }}+ onSaveConnectionSettings={() => setSaved(true)}+ onCopyCommand={() => { if (setup.command) void copyTextToClipboard(setup.command).then((ok) => setNotice(ok ? "已复制命令" : "未能复制命令")); }}+ onNotice={setNotice} />+ </aside>;+}++const genericRegistrations = registeredChannelUiContributions()+ .filter(({ contribution }) => !contribution.Panel && !contribution.ConnectFlow);++export const channelExamples: ComponentExample[] = genericRegistrations.map(({ channel, webui, contribution }, index) => ({+ title: `${contribution.presentation.displayName} · 频道配置`,+ files: [`nanobot/channels/${channel}/${webui}`, ...(index === 0 ? ["webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx"] : [])],+ description: "查看真实频道配置表单与状态。",+ options: "使用频道注册定义、Python 设置契约快照和生产 ChannelSetupSurfaceView。输入、凭据显示、预设、检查与开关只更新当前预览。",+ code: `<ChannelSetupSurfaceView feature={channelFeatures.${channel}} setup={setup} {...displayState} {...actions} />`,+ Preview: () => <ChannelEntryPreview name={channel} />,+}));++export function withChannelEntries(customExamples: ComponentExample[]): ComponentExample[] {+ const assigned = new Set(customExamples.flatMap((example) => example.files));+ return customExamples.map((example) => {+ const entries = registeredChannelUiContributions().filter(({ channel, webui }) => {+ const entry = `nanobot/channels/${channel}/${webui}`;+ const ownsMainView = example.files.some((file) => file.startsWith(`nanobot/channels/${channel}/webui/`)+ && (file.endsWith("PanelView.tsx") || file.endsWith("WhatsAppConnectFlowView.tsx")));+ if (!ownsMainView || assigned.has(entry)) return false;+ assigned.add(entry);+ return true;+ }).map(({ channel, webui }) => `nanobot/channels/${channel}/${webui}`);+ return { ...example, files: [...example.files, ...entries] };+ });+}diff --git a/webui/src/dev/gallery/content.tsx b/webui/src/dev/gallery/content.tsxnew file mode 100644index 000000000..2ee355062--- /dev/null+++ b/webui/src/dev/gallery/content.tsx@@ -0,0 +1,127 @@+import { useState } from "react";++import { FilePreviewPanelView, type FilePreviewPanelState } from "@/components/FilePreviewPanelView";+import { WebPreviewPanelView } from "@/components/WebPreviewPanelView";+import { SessionInfoPopoverView } from "@/components/thread/SessionInfoPopoverView";+import { SubagentThreadView } from "@/components/thread/SubagentThreadView";+import type { AutomationUpdatePayload, SessionAutomationJob, UIMessage } from "@/lib/types";+import { StatePicker, type ComponentExample } from "./example";++function FilePreview() {+ const [mode, setMode] = useState<"text" | "image" | "truncated" | "loading" | "error" | "route_missing">("text");+ const [imageOpen, setImageOpen] = useState(false);+ const path = mode === "image" ? "nanobot.png" : "greeting.ts";+ const state: FilePreviewPanelState = mode === "loading" ? { status: "loading" }+ : mode === "error" || mode === "route_missing" ? { status: "error", routeMissing: mode === "route_missing" }+ : { status: "ready", payload: mode === "image"+ ? { kind: "image", path, display_path: path, project_path: "/workspace", size: 24_576, mime_type: "image/png", data_url: "/brand/nanobot_icon_512.png" }+ : { path, display_path: path, project_path: "/workspace", size: 128, language: "typescript", truncated: mode === "truncated",+ content: 'export const greeting = "Hello, Nanobot";\n\nexport function greet(name: string) {\n return `${greeting}, ${name}`;\n}\n' } };+ return <div className="space-y-4">+ <StatePicker label="文件预览状态" value={mode} options={["text", "image", "truncated", "loading", "error", "route_missing"]}+ onChange={(next) => { setMode(next); setImageOpen(false); }} />+ <div className="flex h-80 flex-col overflow-hidden rounded-control border">+ <FilePreviewPanelView path={path} state={state} imageOpen={imageOpen} onImageOpenChange={setImageOpen}+ onImageError={() => { setMode("error"); setImageOpen(false); }} />+ </div>+ </div>;+}++const localDocument = '<!doctype html><html lang="zh-CN"><meta charset="utf-8"><style>body{font-family:system-ui;padding:32px;color:#252525}h1{font-size:24px}p{line-height:1.7}code{background:#f2f2f2;padding:4px 8px;border-radius:6px}</style><h1>网页预览</h1><p>这段内容来自当前示例的本地文档。</p><p>点击顶部 <code>刷新</code> 按钮,重新显示文档;打开信息按钮查看隔离说明。</p></html>';++function WebsitePreview() {+ const [mode, setMode] = useState<"available" | "native" | "unsupported" | "sameOrigin" | "mixedContent" | "invalid">("available");+ const [revision, setRevision] = useState(0);+ const url = mode === "invalid" ? null : new URL(mode === "sameOrigin" ? window.location.href : "https://example.com/preview");+ return <div className="space-y-4">+ <StatePicker label="网页预览状态" value={mode} options={["available", "native", "unsupported", "sameOrigin", "mixedContent", "invalid"]} onChange={setMode} />+ <div className="flex h-80 flex-col overflow-hidden rounded-control border">+ <WebPreviewPanelView url={url} restriction={mode === "available" ? null : mode} loopback={mode === "sameOrigin"}+ onRefresh={() => setRevision((value) => value + 1)}>+ <iframe key={revision} title="本地示例网页" sandbox="" referrerPolicy="no-referrer" srcDoc={localDocument}+ className="min-h-0 w-full flex-1 border-0 bg-white" />+ </WebPreviewPanelView>+ </div>+ <p role="status" className="text-xs text-muted-foreground">刷新次数:{revision}</p>+ </div>;+}++function exampleJobs(now: number): SessionAutomationJob[] {+ return [+ { id: "gallery-daily-summary", name: "项目摘要", enabled: true, schedule: { kind: "every", every_ms: 3_600_000 },+ payload: { message: "整理当前项目的进展、风险和下一步。" }, state: { next_run_at_ms: now + 3_600_000 },+ origin: { channel: "websocket", chat_id: "gallery", session_key: "websocket:gallery" } },+ { id: "gallery-reminder", name: "代码检查", enabled: false, schedule: { kind: "cron", expr: "0 9 * * 1", tz: "Asia/Shanghai" },+ payload: { message: "检查本周变更并整理待办。" }, state: { last_status: "error", last_error: "Example provider unavailable" } },+ { id: "gallery-local-trigger", name: "发布检查", enabled: true, kind: "local_trigger", schedule: { kind: "local" },+ payload: { kind: "local_trigger", message: "检查发布结果。", command: 'nanobot trigger gallery-local-trigger "检查发布结果"' }, state: {} },+ ];+}++function SessionPreview() {+ const [now] = useState(Date.now);+ const [mode, setMode] = useState<"ready" | "loading" | "error" | "empty" | "action_error">("ready");+ const [jobs, setJobs] = useState(() => exampleJobs(now));+ const [action, setAction] = useState("");+ const saveJob = (job: SessionAutomationJob, values: AutomationUpdatePayload) => {+ if (mode === "action_error") return Promise.reject(new Error("示例保存失败,请重试。"));+ const next = jobs.map((item) => item.id !== job.id ? item : { ...item,+ name: values.name ?? item.name, schedule: values.schedule ?? item.schedule,+ payload: { ...item.payload, message: values.message ?? item.payload.message },+ });+ setJobs(next); setAction("已保存任务"); return Promise.resolve(next);+ };+ return <div className="space-y-4" onClick={(event) => {+ const link = event.target instanceof Element ? event.target.closest('a[href^="#/chat/"]') : null;+ if (link) { event.preventDefault(); setAction("打开示例聊天"); }+ }}>+ <StatePicker label="会话任务状态" value={mode} options={["ready", "loading", "error", "empty", "action_error"]}+ onChange={(next) => { setMode(next); setJobs(exampleJobs(now)); setAction(""); }} />+ <SessionInfoPopoverView title="组件设计" jobs={mode === "ready" || mode === "action_error" ? jobs : []} loading={mode === "loading"} loadFailed={mode === "error"} now={now}+ onOpenCalendar={() => setAction("打开任务日历")}+ onAction={(operation, job) => {+ if (mode === "action_error") return Promise.reject(new Error("示例操作失败,请重试。"));+ const next = operation === "delete" ? jobs.filter((item) => item.id !== job.id) : jobs.map((item) => item.id !== job.id ? item+ : operation === "run" ? { ...item, state: { ...item.state, pending: true } }+ : { ...item, enabled: operation === "enable" });+ setJobs(next); setAction(`${operation}: ${job.name}`); return Promise.resolve(next);+ }} onEdit={saveJob} />+ <p role="status" className="text-sm text-muted-foreground">{action || "打开会话详情,试用任务查看、开关、编辑和删除。"}</p>+ </div>;+}++function SubagentPreview() {+ const [mode, setMode] = useState<"ready" | "running" | "loading" | "error">("ready");+ const [startedAt] = useState(Date.now);+ const [retries, setRetries] = useState(0);+ const messages: UIMessage[] = mode === "loading" || mode === "error" ? [] : [+ { id: "gallery-child-prompt", role: "user", content: "检查配置文件的字段和默认值。", turnId: "gallery-child-turn", createdAt: startedAt },+ { id: "gallery-child-thinking", role: "assistant", content: "", reasoning: "先定位配置定义,再核对默认值。",+ reasoningStreaming: mode === "running", isStreaming: mode === "running", turnId: "gallery-child-turn", createdAt: startedAt + 200 },+ ...(mode === "ready" ? [{ id: "gallery-child-answer", role: "assistant" as const, content: "已核对配置:\n\n- **字段类型** 与默认值一致\n- **目录权限** 由 gateway 执行\n- UI 显示已有配置和保存结果", turnId: "gallery-child-turn", latencyMs: 4_200, createdAt: startedAt + 4_200 }] : []),+ ];+ return <div className="space-y-4">+ <StatePicker label="子任务会话状态" value={mode} options={["ready", "running", "loading", "error"]} onChange={setMode} />+ <div className="max-h-96 overflow-y-auto rounded-control border py-4">+ <SubagentThreadView messages={messages} loading={mode === "loading"} failed={mode === "error"} isStreaming={mode === "running"}+ activeTurnId={mode === "running" ? "gallery-child-turn" : null} runStartedAt={startedAt / 1000}+ onRetry={() => { setRetries((value) => value + 1); setMode("ready"); }} />+ </div>+ <p role="status" className="text-xs text-muted-foreground">重试次数:{retries}</p>+ </div>;+}++export const contentExamples: ComponentExample[] = [+ { title: "FilePreviewPanelView · 文件内容", files: ["webui/src/components/FilePreviewPanelView.tsx"], Preview: FilePreview,+ description: "比较文本、图片、截断、加载和错误显示,点击图片试用缩放。", options: "state 是调用方提供的显示快照;path 决定文件类型和名称;图片打开与失败动作通过回调更新当前预览。",+ code: '<FilePreviewPanelView path={path} state={previewState} imageOpen={imageOpen} onImageOpenChange={setImageOpen} onImageError={reportImageError} />' },+ { title: "WebPreviewPanelView · 网页内容", files: ["webui/src/components/WebPreviewPanelView.tsx"], Preview: WebsitePreview,+ description: "查看网页标题栏、隔离说明和各类限制提示,试用刷新本地文档。", options: "运行时先决定 restriction,再提供网页内容。展示层通过 children 接收内容,通过 onRefresh 请求刷新;此示例的 iframe 使用本地 srcDoc。",+ code: '<WebPreviewPanelView url={url} restriction={restriction} loopback={loopback} onRefresh={refresh}>{frame}</WebPreviewPanelView>' },+ { title: "SessionInfoPopoverView · 会话任务", files: ["webui/src/components/thread/SessionInfoPopoverView.tsx"], Preview: SessionPreview,+ description: "查看任务列表,编辑、停用和删除任务,并切换加载和错误状态。", options: "jobs、loading、loadFailed 和 now 来自调用方;onAction 与 onEdit 返回更新后的任务快照;界面负责弹窗衔接、焦点恢复和操作反馈。",+ code: '<SessionInfoPopoverView title={title} jobs={jobs} loading={loading} loadFailed={failed} now={now} onAction={act} onEdit={edit} onOpenCalendar={openCalendar} />' },+ { title: "SubagentThreadView · 子任务消息", files: ["webui/src/components/thread/SubagentThreadView.tsx"], Preview: SubagentPreview,+ description: "查看子任务消息、推理活动、加载和失败状态,试用重试回调。", options: "messages 已由运行时投影;loading 和 failed 控制提示;isStreaming 与 activeTurnId 决定当前活动。界面不获取任务历史。",+ code: '<SubagentThreadView messages={messages} loading={loading} failed={failed} isStreaming={running} runStartedAt={startedAt} onRetry={retry} />' },+];diff --git a/webui/src/dev/gallery/conversation.tsx b/webui/src/dev/gallery/conversation.tsxnew file mode 100644index 000000000..5f1f20bce--- /dev/null+++ b/webui/src/dev/gallery/conversation.tsx@@ -0,0 +1,325 @@+import { useRef, useState } from "react";++import { FallbackResponseSources } from "@/components/ResponseSourceBadge";+import { AgentActivityCluster } from "@/components/thread/AgentActivityCluster";+import { ComposerUsagePopover, type ComposerRoundUsage } from "@/components/thread/ComposerUsagePopover";+import { ContextCompactionNotice } from "@/components/thread/ContextCompactionNotice";+import { ModelFallbackNotice } from "@/components/thread/ModelFallbackNotice";+import { ModelPresetBadge, type ModelPresetOption } from "@/components/thread/ModelPresetBadge";+import { PromptNavigator } from "@/components/thread/PromptNavigator";+import { RecoveryNotice } from "@/components/thread/RecoveryNotice";+import { StreamErrorNotice } from "@/components/thread/StreamErrorNotice";+import { ThreadComposer } from "@/components/thread/ThreadComposer";+import { ThreadHeader } from "@/components/thread/ThreadHeader";+import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";+import { ThreadMessages } from "@/components/thread/ThreadMessages";+import { ThreadViewport, type ThreadViewportHandle } from "@/components/thread/ThreadViewport";+import { WorkspaceAccessToggle, WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";+import { WebSearchRun } from "@/components/thread/activity/WebSearchRun";+import { Button } from "@/components/ui/button";+import type { StreamError } from "@/lib/nanobot-client";+import { formatToolCallTrace } from "@/lib/tool-traces";+import type { RecoveryState, SlashCommand, ToolProgressEvent, UIContextCompaction, UIMessage, WorkspaceScopePayload, WorkspacesPayload } from "@/lib/types";+import { Sample, StatePicker, type ComponentExample } from "./example";++const createdAt = Date.UTC(2026, 0, 1, 12);+const presets: ModelPresetOption[] = [+ { name: "日常", provider: "openai", model: "gpt-4.1", contextWindowTokens: 1_047_576 },+ { name: "推理", provider: "anthropic", model: "claude-sonnet-4", reasoningEffort: "high", contextWindowTokens: 200_000 },+];+const rounds: ComposerRoundUsage[] = [+ { id: "gallery-round-1", timestamp: createdAt, inputTokens: 8_200, cachedTokens: 6_000, outputTokens: 620, generationMs: 3_100 },+ { id: "gallery-round-2", timestamp: createdAt + 60_000, inputTokens: 12_000, cachedTokens: 8_200, outputTokens: 980, generationMs: 5_400 },+ { id: "gallery-round-3", timestamp: createdAt + 120_000, inputTokens: 18_500, cachedTokens: 12_000, outputTokens: 1_240, generationMs: 7_200 },+];+const commands: SlashCommand[] = [+ { command: "/status", title: "会话状态", description: "查看当前会话状态", icon: "activity", lifecycle: "side_channel", acceptsArgs: false },+ { command: "/compact", title: "压缩上下文", description: "压缩当前会话上下文", icon: "archive", lifecycle: "finalize_active_turn", acceptsArgs: false },+ { command: "/help", title: "命令帮助", description: "查看可用命令", icon: "circle-help", lifecycle: "side_channel", acceptsArgs: false },+];+const projectScope: WorkspaceScopePayload = { project_path: "D:\\Projects\\nanobot", project_name: "nanobot", access_mode: "restricted" };+const workspaceCatalog: WorkspacesPayload = {+ schema_version: 1, default_access_mode: "default", default_scope: projectScope,+ recent_projects: [{ name: "nanobot", path: projectScope.project_path }, { name: "design-system", path: "D:\\Projects\\design-system" }],+ favorite_projects: [{ name: "nanobot", path: projectScope.project_path }],+ controls: { can_change_project: true },+};+const loadExampleProjects = () => Promise.resolve(workspaceCatalog);++const prompts: UIMessage[] = [+ { id: "gallery-prompt-1", role: "user", content: "整理组件的输入、状态和回调。", createdAt },+ { id: "gallery-answer-1", role: "assistant", content: "先从 **模型选择** 和 **消息输入** 开始。\n\n- 调用方提供数据\n- 组件显示状态\n- 回调更新当前选择", latencyMs: 4_200, createdAt: createdAt + 1_000 },+ { id: "gallery-prompt-2", role: "user", content: "给消息列表加入代码和引用示例。", createdAt: createdAt + 60_000 },+ { id: "gallery-answer-2", role: "assistant", content: "代码块支持复制:\n\n```tsx\n<ThreadMessages messages={messages} />\n```\n\n选中这段回复中的文字,可以试用引用操作。", latencyMs: 5_200, createdAt: createdAt + 61_000 },+ { id: "gallery-prompt-3", role: "user", content: "长会话如何跳转到之前的问题?", createdAt: createdAt + 120_000 },+ { id: "gallery-answer-3", role: "assistant", content: "打开问题导航后,可以搜索问题并跳转。\n\n滚动区域左侧的标记也对应每个问题。鼠标停留时会显示问题和回复摘要。", latencyMs: 2_600, createdAt: createdAt + 121_000 },+];+const longConversation: UIMessage[] = Array.from({ length: 8 }, (_, index) => [+ { id: `gallery-long-prompt-${index}`, role: "user" as const, content: `问题 ${index + 1}:${["模型配置", "工作目录", "消息排版", "工具活动"][index % 4]}如何展示?`, createdAt: createdAt + index * 60_000 },+ { id: `gallery-long-answer-${index}`, role: "assistant" as const, content: "组件接收已有状态,并把操作交给调用方。\n\n- 可以查看历史问题\n- 可以复制回复内容\n- 可以在回复后创建会话分支\n\n这段示例内容使预览产生真实滚动距离,便于体验问题标记和返回底部按钮。", latencyMs: 3_200, createdAt: createdAt + index * 60_000 + 1_000 },+]).flat();++function ComposerPreview() {+ const [mode, setMode] = useState<"thread" | "hero" | "streaming" | "disabled">("thread");+ const [preset, setPreset] = useState(presets[0].name);+ const [sent, setSent] = useState("");+ const [quoted, setQuoted] = useState<string | null>(null);+ const selected = presets.find((option) => option.name === preset) ?? presets[0];+ return <div className="space-y-4">+ <StatePicker label="输入状态" value={mode} options={["thread", "hero", "streaming", "disabled"]} onChange={setMode} />+ <Button variant="outline" size="sm" onClick={() => setQuoted("组件接收状态,并把操作交给调用方。")}>加入引用</Button>+ <ThreadComposer disabled={mode === "disabled"} isStreaming={mode === "streaming"} variant={mode === "hero" ? "hero" : "thread"}+ inputAriaLabel="示例消息" placeholder="输入消息,或输入 / 查看命令"+ modelLabel={selected.name} modelDetail={selected.model} modelProvider={selected.provider} modelPreset={preset}+ modelPresets={presets} onModelPresetChange={setPreset} slashCommands={commands}+ contextUsage={{ contextTokens: 18_500, contextWindowTokens: 200_000 }} recentRoundUsage={rounds}+ workspaceScope={projectScope} workspaceControlsHidden quotedContext={quoted} onQuotedContextChange={setQuoted}+ onStop={() => { setMode("thread"); setSent("已停止示例任务"); }}+ onSend={(content, attachments) => { setSent(`${content}${attachments?.length ? ` · ${attachments.length} 个附件` : ""}`); return true; }} />+ <p role="status" className="text-sm text-muted-foreground">{sent ? `提交内容:${sent}` : "试用消息提交、附件选择、模型切换和命令菜单。"}</p>+ </div>;+}++function ModelPresetPreview() {+ const [preset, setPreset] = useState(presets[0].name);+ const [mode, setMode] = useState<"ready" | "setup" | "hero">("ready");+ const [action, setAction] = useState("");+ const selected = presets.find((option) => option.name === preset) ?? presets[0];+ return <div className="space-y-4">+ <StatePicker label="模型控件状态" value={mode} options={["ready", "setup", "hero"]} onChange={setMode} />+ <ModelPresetBadge label={mode === "setup" ? "配置模型" : selected.name} modelPreset={preset} modelPresets={presets}+ provider={selected.provider} modelDetail={selected.model} isHero={mode === "hero"} needsSetup={mode === "setup"}+ onPresetChange={setPreset} onManageModels={() => setAction("打开模型管理")}+ onClick={() => setAction("打开模型设置")} />+ <p role="status" className="text-sm text-muted-foreground">{action || `当前预设:${preset}。打开菜单或用方向键切换。`}</p>+ </div>;+}++function UsagePreview() {+ const [mode, setMode] = useState<"normal" | "caution" | "critical" | "rounds_only" | "sheet">("normal");+ const tokens = mode === "critical" ? 192_000 : mode === "caution" ? 162_000 : 18_500;+ return <div className="space-y-4">+ <StatePicker label="用量状态" value={mode} options={["normal", "caution", "critical", "rounds_only", "sheet"]} onChange={setMode} />+ <ComposerUsagePopover context={mode === "rounds_only" ? null : { contextTokens: tokens, contextWindowTokens: 200_000 }}+ rounds={rounds} showLabel bottomSheet={mode === "sheet"} />+ <p className="text-sm text-muted-foreground">打开用量详情,查看上下文占用、缓存和各轮生成时间。</p>+ </div>;+}++function WorkspacePreview() {+ const [scope, setScope] = useState(projectScope);+ const [mode, setMode] = useState<"ready" | "disabled">("ready");+ return <div className="space-y-4">+ <StatePicker label="工作目录状态" value={mode} options={["ready", "disabled"]} onChange={setMode} />+ <div className="flex flex-wrap items-center gap-3">+ <WorkspaceProjectPicker isHero scope={scope} defaultScope={projectScope} controls={workspaceCatalog.controls}+ disabled={mode === "disabled"} onLoadProjects={loadExampleProjects} onChange={setScope} />+ <WorkspaceAccessToggle scope={scope} isHero disabled={mode === "disabled"} onChange={setScope} />+ </div>+ <p role="status" className="text-sm text-muted-foreground">{scope.project_path} · {scope.access_mode}</p>+ </div>;+}++function NavigatorPreview() {+ const [selected, setSelected] = useState("");+ return <div className="space-y-4">+ <div className="flex items-center gap-3"><PromptNavigator messages={prompts} onJumpToPrompt={setSelected} />+ <span className="text-sm text-muted-foreground">打开问题导航,搜索并选择问题。</span></div>+ <p role="status" className="text-sm text-muted-foreground">{prompts.find((message) => message.id === selected)?.content ?? "尚未选择问题"}</p>+ </div>;+}++function HeaderPreview() {+ const [theme, setTheme] = useState<"light" | "dark">("light");+ const [temporary, setTemporary] = useState(false);+ const [action, setAction] = useState("");+ return <div className="space-y-4">+ <div className="rounded-control border [--thread-header-position:relative]">+ <ThreadHeader title="组件使用示例" handle={{ id: "handle_11111111111111111111111111111111", name: "gallery" }}+ theme={theme} onToggleTheme={() => setTheme((value) => value === "light" ? "dark" : "light")}+ onToggleSidebar={() => setAction("切换侧栏")} temporaryChatEnabled={temporary} onTemporaryChatEnabledChange={setTemporary}+ promptNavigatorAction={<PromptNavigator messages={prompts} onJumpToPrompt={(id) => setAction(`跳转到 ${id}`)} />} />+ </div>+ <p role="status" className="text-sm text-muted-foreground">{action || "试用标题栏操作"} · {theme} · {temporary ? "临时会话" : "普通会话"}</p>+ </div>;+}++function MessagesPreview() {+ const [quoted, setQuoted] = useState("");+ const [fork, setFork] = useState<number | null>(null);+ return <div className="space-y-4">+ <div className="max-h-[30rem] overflow-y-auto rounded-control border px-4 py-5">+ <ThreadMessages messages={prompts} onQuoteSelection={setQuoted} onForkFromMessage={setFork} />+ </div>+ <p role="status" className="text-sm text-muted-foreground">{quoted ? `引用:${quoted}` : fork !== null ? `从第 ${fork + 1} 个问题创建分支` : "打开消息菜单,或选中回复文字后点击引用。"}</p>+ </div>;+}++function ViewportPreview() {+ const viewport = useRef<ThreadViewportHandle>(null);+ const [mode, setMode] = useState<"history" | "empty">("history");+ const [action, setAction] = useState("");+ return <div className="space-y-4">+ <StatePicker label="会话视图" value={mode} options={["history", "empty"]} onChange={setMode} />+ <div className="flex h-[28rem] flex-col overflow-hidden rounded-control border">+ <div className="shrink-0 border-b px-3 py-2"><PromptNavigator messages={mode === "history" ? longConversation : []}+ onJumpToPrompt={(id) => viewport.current?.jumpToUserPrompt(id)} /></div>+ <ThreadViewport ref={viewport} messages={mode === "history" ? longConversation : []} isStreaming={false}+ conversationKey={`gallery-${mode}`} conversationReady onForkFromMessage={(index) => setAction(`从问题 ${index + 1} 创建分支`)}+ emptyState={<p className="text-sm text-muted-foreground">输入消息开始会话</p>} />+ </div>+ <p role="status" className="text-sm text-muted-foreground">{action || "滚动查看问题标记,或用导航跳转并返回底部。"}</p>+ </div>;+}++function HistoryPreview() {+ const [mode, setMode] = useState<"loading" | "error" | "pulling">("error");+ const [retries, setRetries] = useState(0);+ return <div className="space-y-4">+ <StatePicker label="历史加载状态" value={mode} options={["loading", "error", "pulling"]} onChange={setMode} />+ <div className="relative h-20 rounded-control border">+ <ThreadHistoryStatus loading={mode === "loading"} error={mode === "error" ? "Example history unavailable" : null}+ pullDistance={mode === "pulling" ? 32 : 0} onRetry={() => { setRetries((value) => value + 1); setMode("loading"); }} />+ </div>+ <p role="status" className="text-sm text-muted-foreground">重试次数:{retries}</p>+ </div>;+}++function RecoveryPreview() {+ const [mode, setMode] = useState<"awaiting_user" | "resuming" | "failed" | "unavailable">("awaiting_user");+ const [action, setAction] = useState("");+ const [visible, setVisible] = useState(true);+ const state: RecoveryState = { recovery_id: `gallery-recovery-${mode}`, status: mode === "unavailable" ? "failed" : mode, can_continue: mode !== "unavailable" };+ return <div className="space-y-4">+ <StatePicker label="恢复状态" value={mode} options={["awaiting_user", "resuming", "failed", "unavailable"]}+ onChange={(value) => { setMode(value); setVisible(true); setAction(""); }} />+ {visible ? <RecoveryNotice state={state} onContinue={() => { setVisible(false); setAction("继续示例任务"); return Promise.resolve(); }}+ onDismiss={() => { setVisible(false); setAction("已关闭恢复提示"); return Promise.resolve(); }} /> : null}+ <Button variant="outline" size="sm" onClick={() => { setVisible(true); setAction(""); }}>重置预览</Button>+ <p role="status" className="text-sm text-muted-foreground">{action || "选择恢复状态,再试用继续或关闭。"}</p>+ </div>;+}++function FallbackPreview() {+ const [mode, setMode] = useState<"fallback" | "reauth">("fallback");+ const [dismissed, setDismissed] = useState(false);+ const [action, setAction] = useState("");+ return <div className="space-y-4">+ <StatePicker label="模型回退状态" value={mode} options={["fallback", "reauth"]} onChange={(value) => { setMode(value); setDismissed(false); }} />+ {!dismissed ? <ModelFallbackNotice model="gpt-4.1" reauthProvider={mode === "reauth" ? "openai" : undefined}+ reauthProviderLabel={mode === "reauth" ? "OpenAI" : undefined} onDismiss={() => setDismissed(true)}+ onOpenSettings={() => setAction("打开模型设置")} /> : null}+ <Button variant="outline" size="sm" onClick={() => setDismissed(false)}>重新显示</Button>+ <p role="status" className="text-sm text-muted-foreground">{action || "试用模型设置入口与关闭按钮。"}</p>+ </div>;+}++function CompactionPreview() {+ const [phase, setPhase] = useState<UIContextCompaction["phase"]>("started");+ return <><StatePicker label="上下文压缩阶段" value={phase} options={["started", "succeeded", "failed", "cancelled"]} onChange={setPhase} />+ <ContextCompactionNotice compaction={{ id: "gallery-compaction", phase, announce: true }} /></>;+}++const errors: Record<StreamError["kind"], StreamError> = {+ message_too_big: { kind: "message_too_big" },+ workspace_scope_rejected: { kind: "workspace_scope_rejected" },+ turn_rejected: { kind: "turn_rejected", chatId: "gallery", turnId: "gallery-turn" },+ model_request_failed: { kind: "model_request_failed", chatId: "gallery", errorKind: "rate_limit", attempts: 3 },+};++function ErrorPreview() {+ const [kind, setKind] = useState<StreamError["kind"]>("model_request_failed");+ const [dismissed, setDismissed] = useState(false);+ return <div className="space-y-4">+ <StatePicker label="消息错误类型" value={kind} options={["message_too_big", "workspace_scope_rejected", "turn_rejected", "model_request_failed"]}+ onChange={(value) => { setKind(value); setDismissed(false); }} />+ {!dismissed ? <StreamErrorNotice error={errors[kind]} onDismiss={() => setDismissed(true)} /> : null}+ <Button variant="outline" size="sm" onClick={() => setDismissed(false)}>重新显示</Button>+ </div>;+}++function ClusterPreview() {+ const [status, setStatus] = useState<"running" | "done" | "error">("done");+ const [expanded, setExpanded] = useState(true);+ const [startedAt] = useState(Date.now);+ const event: ToolProgressEvent = { call_id: "gallery-read", name: "read_file", arguments: { path: "webui/src/components/thread/ThreadComposer.tsx" },+ phase: status === "running" ? "start" : status === "error" ? "error" : "end", error: status === "error" ? "File could not be read." : undefined };+ const trace = formatToolCallTrace(event) ?? "read_file()";+ const messages: UIMessage[] = [+ { id: "gallery-reasoning", role: "assistant", content: "", reasoning: "先核对组件接口,再查看消息和模型控件的组合方式。", reasoningStreaming: status === "running", isStreaming: status === "running", createdAt: startedAt },+ { id: "gallery-tool", role: "tool", kind: "trace", content: trace, traces: [trace], toolEvents: [event], createdAt: startedAt + 1_000 },+ ];+ return <><StatePicker label="活动状态" value={status} options={["running", "done", "error"]} onChange={setStatus} />+ <AgentActivityCluster messages={messages} isTurnStreaming={status === "running"} hasBodyBelow={false}+ startedAtMs={startedAt} turnLatencyMs={4_800} expanded={expanded} onExpandedChange={setExpanded} /></>;+}++function SearchActivityPreview() {+ const [status, setStatus] = useState<"running" | "done" | "error">("done");+ const [target, setTarget] = useState<"web" | "x">("web");+ return <><StatePicker label="搜索状态" value={status} options={["running", "done", "error"]} onChange={setStatus} />+ <StatePicker label="搜索来源" value={target} options={["web", "x"]} onChange={setTarget} />+ <WebSearchRun turnActive={status === "running"} run={{ key: "gallery-search", query: "React component composition", target, status,+ sources: status === "done" && target === "web" ? [{ title: "React · Passing props to a component", href: "https://react.dev/learn/passing-props-to-a-component", host: "react.dev", displayUrl: "react.dev/learn/passing-props-to-a-component" }] : [] }} /></>;+}++function ResponseSourcesPreview() {+ return <Sample label="点击回退标记查看响应时的预设、模型与供应商">+ <FallbackResponseSources sources={[+ { preset: "日常", model: "gpt-4.1", provider: "openai", fallback: true },+ { preset: "推理", model: "claude-sonnet-4", provider: "anthropic", fallback: true },+ ]} />+ </Sample>;+}++const components = "webui/src/components/";+export const conversationExamples: ComponentExample[] = [+ { title: "ThreadComposer · 消息输入", files: ["thread/ThreadComposer"], Preview: ComposerPreview,+ description: "直接试用消息提交、附件、命令和引用,并切换忙碌与禁用状态。", options: "onSend 返回成功后清空输入;isStreaming 控制停止与排队;variant 切换会话和欢迎页样式。示例提交保存在当前预览。",+ code: '<ThreadComposer onSend={send} modelPresets={presets} onModelPresetChange={setPreset} slashCommands={commands} />' },+ { title: "ModelPresetBadge · 模型预设", files: ["thread/ModelPresetBadge"], Preview: ModelPresetPreview,+ description: "打开模型菜单,体验预设切换、键盘操作和待配置状态。", options: "modelPresets 提供预设快照,modelPreset 与 onPresetChange 控制当前选择;needsSetup 显示配置入口。",+ code: '<ModelPresetBadge label={preset} modelPreset={preset} modelPresets={presets} onPresetChange={setPreset} isHero={false} />' },+ { title: "ComposerUsagePopover · 上下文用量", files: ["thread/ComposerUsagePopover"], Preview: UsagePreview,+ description: "查看上下文占用、缓存和生成时间,切换警戒状态与底部面板。", options: "context 提供上下文容量,rounds 提供各轮统计;bottomSheet 选择移动端面板。",+ code: '<ComposerUsagePopover context={{ contextTokens: 18500, contextWindowTokens: 200000 }} rounds={rounds} showLabel />' },+ { title: "WorkspaceControls · 工作目录", files: ["thread/WorkspaceControls"], Preview: WorkspacePreview,+ description: "选择示例项目,并切换当前预览的访问模式。", options: "scope 与 onChange 控制当前选择;onLoadProjects 提供示例目录列表。真实路径解析和权限执行由 gateway 负责。",+ code: '<WorkspaceProjectPicker isHero scope={scope} defaultScope={defaultScope} controls={controls} onLoadProjects={loadProjects} onChange={setScope} />\n<WorkspaceAccessToggle scope={scope} isHero onChange={setScope} />' },+ { title: "PromptNavigator · 问题导航", files: ["thread/PromptNavigator"], Preview: NavigatorPreview,+ description: "打开问题列表,搜索历史问题并查看跳转回调。", options: "messages 提供完整消息列表,组件提取用户问题;onJumpToPrompt 接收目标消息 ID。",+ code: '<PromptNavigator messages={messages} onJumpToPrompt={jumpToPrompt} />' },+ { title: "ThreadHeader · 会话标题栏", files: ["thread/ThreadHeader"], Preview: HeaderPreview,+ description: "试用侧栏、主题、临时会话和问题导航控件。", options: "title、handle、theme 与 temporaryChatEnabled 提供显示状态;各操作通过回调交给调用方。",+ code: '<ThreadHeader title="Component examples" theme={theme} onToggleTheme={toggleTheme} onToggleSidebar={toggleSidebar} />' },+ { title: "ThreadMessages · 消息列表", files: ["thread/ThreadMessages", "thread/AssistantSelectionAction"], Preview: MessagesPreview,+ description: "查看完整多轮消息组合,试用消息菜单、会话分支和选中文本引用。", options: "messages 为已投影消息;onForkFromMessage 接收用户问题索引,onQuoteSelection 接收所选回复文字。",+ code: '<ThreadMessages messages={messages} onForkFromMessage={forkFromMessage} onQuoteSelection={quoteText} />' },+ { title: "ThreadViewport · 会话滚动", files: ["thread/ThreadViewport", "thread/PromptRail"], Preview: ViewportPreview,+ description: "真实长会话滚动区,包含问题标记、导航跳转和返回底部。", options: "固定预览容器高度;messages 驱动历史显示,ref.jumpToUserPrompt 执行定位;emptyState 提供空会话内容。",+ code: '<div className="flex h-96 flex-col"><ThreadViewport ref={viewport} messages={messages} isStreaming={false} /></div>' },+ { title: "ThreadHistoryStatus · 历史加载", files: ["thread/ThreadHistoryStatus"], Preview: HistoryPreview,+ description: "切换加载、失败和下拉状态,并试用重试按钮。", options: "loading 控制加载指示,error 控制错误提示,pullDistance 控制下拉位置,onRetry 由调用方提供。",+ code: '<ThreadHistoryStatus loading={loading} error={error} onRetry={retry} />' },+ { title: "RecoveryNotice · 任务恢复", files: ["thread/RecoveryNotice"], Preview: RecoveryPreview,+ description: "切换中断、恢复、失败和无法继续状态,试用继续与关闭。", options: "state 为已有恢复快照;onContinue 与 onDismiss 返回 Promise。示例回调只更新当前预览。",+ code: '<RecoveryNotice state={recoveryState} onContinue={continueTask} onDismiss={dismissRecovery} />' },+ { title: "ModelFallbackNotice · 模型回退", files: ["thread/ModelFallbackNotice"], Preview: FallbackPreview,+ description: "查看回退模型与授权失效提示,试用设置入口和关闭操作。", options: "model 标识回退模型;reauthProviderLabel 显示授权到期提示;onOpenSettings 和 onDismiss 由调用方提供。",+ code: '<ModelFallbackNotice model="gpt-4.1" onDismiss={dismiss} onOpenSettings={openModelSettings} />' },+ { title: "ContextCompactionNotice · 上下文压缩", files: ["thread/ContextCompactionNotice"], Preview: CompactionPreview,+ description: "比较压缩开始、成功、失败和取消时的显示。", options: "compaction.phase 决定提示,announce 控制屏幕阅读器播报。",+ code: '<ContextCompactionNotice compaction={{ id: "compaction-1", phase: "succeeded", announce: true }} />' },+ { title: "StreamErrorNotice · 消息错误", files: ["thread/StreamErrorNotice"], Preview: ErrorPreview,+ description: "比较消息大小、目录权限、任务拒绝和模型请求失败的提示。", options: "error.kind 决定错误文案;onDismiss 关闭提示。",+ code: '<StreamErrorNotice error={{ kind: "message_too_big" }} onDismiss={dismiss} />' },+ { title: "AgentActivityCluster · 完整活动", files: ["thread/AgentActivityCluster"], Preview: ClusterPreview,+ description: "用真实活动容器展示推理和工具记录,切换运行、完成和失败。", options: "messages 包含已有 reasoning 和 trace 投影;isTurnStreaming 控制活动状态;expanded 可由调用方控制。",+ code: '<AgentActivityCluster messages={activityMessages} isTurnStreaming={running} hasBodyBelow={false} expanded={expanded} onExpandedChange={setExpanded} />' },+ { title: "WebSearchRun · 搜索活动", files: ["thread/activity/WebSearchRun", "thread/activity/WebActivityRow"], Preview: SearchActivityPreview,+ description: "查看搜索进度与结果来源,切换网页和 X 搜索样式。", options: "run 为搜索显示快照,包含 query、target、status 和 sources;turnActive 控制运行效果。结果站点图标由共享组件加载。",+ code: '<WebSearchRun run={searchRun} turnActive={running} />' },+ { title: "FallbackResponseSources · 响应来源", files: ["ResponseSourceBadge"], Preview: ResponseSourcesPreview,+ description: "查看历史回复使用的回退预设、模型和供应商。", options: "sources 保留响应时的模型快照,仅 fallback 为 true 的来源显示标记。",+ code: '<FallbackResponseSources sources={[{ provider: "openai", model: "gpt-4.1", preset: "Daily", fallback: true }]} />' },+].map((example) => ({ ...example, files: example.files.map((file) => `${components}${file}.tsx`) }));diff --git a/webui/src/dev/gallery/example.tsx b/webui/src/dev/gallery/example.tsxnew file mode 100644index 000000000..4b6179ce4--- /dev/null+++ b/webui/src/dev/gallery/example.tsx@@ -0,0 +1,37 @@+import type { ComponentType, ReactNode } from "react";++import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";++export interface ComponentExample {+ title: string;+ files: string[];+ description: string;+ options: string;+ code: string;+ Preview: ComponentType;+}++export function Sample({ label, children }: { label: string; children: ReactNode }) {+ return <div className="min-w-0 space-y-2">+ <p className="text-xs text-muted-foreground">{label}</p>+ {children}+ </div>;+}++export function StatePicker<T extends string>({ label, value, options, onChange }: {+ label: string;+ value: T;+ options: readonly T[];+ onChange: (value: T) => void;+}) {+ return <div className="mb-5 flex flex-wrap items-center gap-3 text-sm">+ <span>{label}</span>+ <Select value={value} onValueChange={(next) => {+ const option = options.find((item) => item === next);+ if (option) onChange(option);+ }}>+ <SelectTrigger aria-label={label} className="min-w-36"><SelectValue /></SelectTrigger>+ <SelectContent>{options.map((option) => <SelectItem key={option} value={option}>{option}</SelectItem>)}</SelectContent>+ </Select>+ </div>;+}diff --git a/webui/src/dev/gallery/foundations.tsx b/webui/src/dev/gallery/foundations.tsxnew file mode 100644index 000000000..b7fef3414--- /dev/null+++ b/webui/src/dev/gallery/foundations.tsx@@ -0,0 +1,280 @@+import { useState } from "react";+import { Plus } from "lucide-react";++import { Button } from "@/components/ui/button";+import { Input, SearchInput } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { ToggleButton } from "@/components/ui/toggle-button";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { SegmentedControl } from "@/components/ui/segmented-control";+import { ComboboxOption, useComboboxNavigation } from "@/components/ui/combobox";+import { ControlChevron } from "@/components/ui/control-chevron";+import { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { Sheet, SheetContent, SheetDescription, SheetTitle, SheetTrigger } from "@/components/ui/sheet";+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { HoverHint, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, TruncatedTextTooltip } from "@/components/ui/tooltip";+import { Disclosure } from "@/components/ui/disclosure";+import { ExpandableText } from "@/components/ui/expandable-text";+import { StreamingLabelSheen } from "@/components/ui/streaming-label-sheen";+import { Sample, type ComponentExample } from "./example";++function Buttons() {+ const [clicks, setClicks] = useState(0);+ return <div className="space-y-6">+ <Sample label="Variants · 同一个按钮的不同样式">+ <div className="flex flex-wrap items-center gap-3">+ {(["default", "secondary", "outline", "ghost", "destructive", "link"] as const).map((variant) =>+ <Button key={variant} variant={variant} onClick={() => setClicks((value) => value + 1)}>{variant}</Button>)}+ <Button variant="icon" size="icon" aria-label="Add example" onClick={() => setClicks((value) => value + 1)}><Plus className="h-4 w-4" /></Button>+ </div>+ </Sample>+ <Sample label="Sizes · 尺寸">+ <div className="flex flex-wrap items-center gap-3">+ {(["sm", "default", "control", "lg"] as const).map((size) =>+ <Button key={size} size={size} variant="outline" onClick={() => setClicks((value) => value + 1)}>{size}</Button>)}+ <Button disabled>Unavailable</Button>+ </div>+ </Sample>+ <p role="status" className="text-sm text-muted-foreground">Button clicks: {clicks}</p>+ </div>;+}++function Inputs() {+ return <div className="grid gap-5 sm:grid-cols-2">+ <Sample label="Default"><Input aria-label="Example name" placeholder="Project name" /></Sample>+ <Sample label="Search"><SearchInput aria-label="Example search" placeholder="Search projects" /></Sample>+ <Sample label="Invalid"><Input aria-label="Invalid name" aria-invalid="true" aria-describedby="gallery-input-error" defaultValue="" />+ <p id="gallery-input-error" className="text-xs text-destructive">Enter a project name.</p></Sample>+ <Sample label="Disabled"><Input aria-label="Disabled name" disabled defaultValue="Unavailable" /></Sample>+ </div>;+}++function Textareas() {+ return <div className="grid gap-5 sm:grid-cols-2">+ <Textarea aria-label="Example notes" defaultValue="Write a short note…" />+ <Textarea aria-label="Disabled notes" disabled defaultValue="Read-only preview" />+ </div>;+}++function Switches() {+ const [checked, setChecked] = useState(false);+ return <div className="space-y-5">+ <div className="flex items-center justify-between gap-4 text-sm"><span>Enable example</span>+ <ToggleButton checked={checked} onChange={setChecked} label="Enable example" /></div>+ <p role="status" className="text-sm text-muted-foreground">{checked ? "Enabled" : "Disabled"}</p>+ <div className="flex gap-8">+ <ToggleButton checked disabled onChange={() => {}} label="Unavailable enabled switch" />+ <ToggleButton checked={false} disabled onChange={() => {}} label="Unavailable disabled switch" />+ </div>+ </div>;+}++function Selects() {+ const [value, setValue] = useState("default");+ return <div className="flex flex-wrap items-center gap-4">+ <Select value={value} onValueChange={setValue}>+ <SelectTrigger aria-label="Example model" className="min-w-40"><SelectValue /></SelectTrigger>+ <SelectContent><SelectItem value="default">Default</SelectItem><SelectItem value="fast">Fast</SelectItem>+ <SelectItem value="offline" disabled>Unavailable</SelectItem></SelectContent>+ </Select>+ <Select disabled value="default"><SelectTrigger aria-label="Disabled model"><SelectValue /></SelectTrigger>+ <SelectContent><SelectItem value="default">Default</SelectItem></SelectContent></Select>+ <p role="status" className="text-sm text-muted-foreground">Selected: {value}</p>+ </div>;+}++function Segments() {+ const [value, setValue] = useState("day");+ return <div className="space-y-4">+ <SegmentedControl value={value} onChange={setValue} mode="tabs" ariaLabel="Example period"+ options={[{ value: "day", label: "Day" }, { value: "week", label: "Week" }, { value: "month", label: "Month" }]} />+ <p role="status" className="text-sm text-muted-foreground">Selected period: {value}</p>+ </div>;+}++function Comboboxes() {+ const [query, setQuery] = useState("");+ const [selected, setSelected] = useState("Alpha");+ const [open, setOpen] = useState(false);+ const values = ["Alpha", "Beta", "Gamma"].filter((name) => name.toLowerCase().includes(query.toLowerCase()));+ const select = (value: string) => { setSelected(value); setQuery(value); setOpen(false); };+ const navigation = useComboboxNavigation({ open, values, selectedValue: selected, onSelect: select, onClose: () => setOpen(false) });+ return <div className="max-w-sm space-y-3">+ <Input {...navigation.inputProps} aria-label="Search example options" value={query} placeholder="Type or use arrow keys"+ onFocus={() => setOpen(true)} onChange={(event) => { setQuery(event.target.value); setOpen(true); }} />+ {open && values.length > 0 ? <div {...navigation.listProps} aria-label="Example options" className="rounded-control border p-1">+ {values.map((value) => <ComboboxOption key={value} {...navigation.getOptionProps(value)}>{value}</ComboboxOption>)}+ </div> : null}+ {open && values.length === 0 ? <p role="status" className="text-sm text-muted-foreground">No matching options</p> : null}+ <p className="text-sm text-muted-foreground">Selected option: {selected}</p>+ </div>;+}++function Dialogs() {+ const [open, setOpen] = useState(false);+ const [name, setName] = useState("Nanobot");+ const [draft, setDraft] = useState(name);+ return <div className="space-y-4">+ <Dialog open={open} onOpenChange={(next) => { setOpen(next); if (next) setDraft(name); }}>+ <DialogTrigger asChild><Button variant="outline">Open dialog</Button></DialogTrigger>+ <DialogContent><DialogHeader><DialogTitle>Edit example label</DialogTitle>+ <DialogDescription>Changes apply only to this preview.</DialogDescription></DialogHeader>+ <Input aria-label="Example label" value={draft} onChange={(event) => setDraft(event.target.value)} />+ <Selects />+ <DialogFooter><DialogClose asChild><Button variant="outline">Cancel</Button></DialogClose>+ <Button onClick={() => { setName(draft); setOpen(false); }}>Save label</Button></DialogFooter>+ </DialogContent>+ </Dialog>+ <p role="status" className="text-sm text-muted-foreground">Saved label: {name}</p>+ </div>;+}++function Alerts() {+ const [removed, setRemoved] = useState(false);+ const [open, setOpen] = useState(false);+ return <div className="space-y-4">+ <Button variant="destructive" onClick={() => setOpen(true)}>Remove example</Button>+ <AlertDialog open={open} onOpenChange={setOpen}>+ <AlertDialogContent><AlertDialogHeader><AlertDialogTitle>Remove this example?</AlertDialogTitle>+ <AlertDialogDescription>This changes only the preview state.</AlertDialogDescription></AlertDialogHeader>+ <AlertDialogFooter><AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction onClick={() => setRemoved(true)}>Confirm removal</AlertDialogAction></AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ <p role="status" className="text-sm text-muted-foreground">{removed ? "Example removed." : "Example available."}</p>+ </div>;+}++function Sheets() {+ return <Sheet><SheetTrigger asChild><Button variant="outline">Open sheet</Button></SheetTrigger>+ <SheetContent><SheetTitle>Example side panel</SheetTitle><SheetDescription>Supporting controls beside the current page.</SheetDescription>+ <div className="mt-6"><Input aria-label="Panel notes" placeholder="Try editing here" /></div></SheetContent>+ </Sheet>;+}++function Popovers() {+ return <Popover><PopoverTrigger asChild><Button variant="outline">Open popover</Button></PopoverTrigger>+ <PopoverContent className="w-64 p-4"><label className="space-y-2 text-sm"><span>Quick note</span><Input aria-label="Quick note" /></label></PopoverContent>+ </Popover>;+}++function Menus() {+ const [density, setDensity] = useState("comfortable");+ const [action, setAction] = useState("None");+ return <div className="space-y-4">+ <DropdownMenu><DropdownMenuTrigger asChild><Button variant="outline">View options</Button></DropdownMenuTrigger>+ <DropdownMenuContent><DropdownMenuLabel>Layout</DropdownMenuLabel>+ <DropdownMenuRadioGroup value={density} onValueChange={setDensity}>+ <DropdownMenuRadioItem value="comfortable">Comfortable</DropdownMenuRadioItem>+ <DropdownMenuRadioItem value="compact">Compact</DropdownMenuRadioItem>+ </DropdownMenuRadioGroup><DropdownMenuSeparator />+ <DropdownMenuItem onSelect={() => setAction("Rename")}>Rename</DropdownMenuItem>+ <DropdownMenuSub><DropdownMenuSubTrigger>More actions</DropdownMenuSubTrigger><DropdownMenuSubContent>+ <DropdownMenuItem onSelect={() => setAction("Duplicate")}>Duplicate</DropdownMenuItem>+ </DropdownMenuSubContent></DropdownMenuSub>+ <DropdownMenuItem disabled>Unavailable</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <p role="status" className="text-sm text-muted-foreground">Density: {density}. Action: {action}.</p>+ </div>;+}++function Tooltips() {+ return <div className="flex flex-wrap items-center gap-4">+ <TooltipProvider><Tooltip><TooltipTrigger asChild><Button variant="outline">Primitive tooltip</Button></TooltipTrigger>+ <TooltipContent>Shared pointer delay and immediate keyboard focus.</TooltipContent></Tooltip></TooltipProvider>+ <HoverHint content="A composed hint with the same focus and pointer behavior."><Button variant="outline">Hover hint</Button></HoverHint>+ </div>;+}++function TruncatedText() {+ return <div className="space-y-4">+ <TruncatedTextTooltip tabIndex={0} className="block max-w-48 text-sm" text="A long project name whose full text stays available on focus" />+ <TruncatedTextTooltip tabIndex={0} className="block max-w-48 text-sm" text="Short name" />+ </div>;+}++function Disclosures() {+ return <Disclosure summary={<span className="text-sm font-medium">Show advanced options</span>}+ summaryClassName="rounded-control border p-3" contentClassName="space-y-3 p-3">+ <p className="text-sm text-muted-foreground">This draft survives closing and reopening.</p>+ <Input aria-label="Disclosure draft" defaultValue="Keep this draft" />+ </Disclosure>;+}++function Expandable() {+ const [expanded, setExpanded] = useState(false);+ return <div className="max-w-sm space-y-3">+ <ExpandableText expanded={expanded} lines={2} id="gallery-expandable" className="text-sm leading-6">+ {"A longer activity description can stay compact while preserving its full text. Expand this example to read all of it, then collapse it again. The same paragraph remains mounted throughout the animation, so selection and layout do not jump between duplicate copies."}+ </ExpandableText>+ <Button variant="outline" size="sm" aria-expanded={expanded} aria-controls="gallery-expandable"+ onClick={() => setExpanded((value) => !value)}>{expanded ? "Show less" : "Show more"}</Button>+ </div>;+}++function StreamingLabels() {+ const [active, setActive] = useState(true);+ return <div className="space-y-4">+ <ToggleButton label="Animate label" checked={active} onChange={setActive} />+ <StreamingLabelSheen active={active}>Working through the next step…</StreamingLabelSheen>+ </div>;+}++const base = "webui/src/components/ui/";+export const foundationExamples: ComponentExample[] = [+ { title: "Button · 按钮", files: ["button"], Preview: Buttons,+ description: "One button, several appearances and sizes. 同一组件通过选项变化。",+ options: "variant changes appearance; size changes dimensions; disabled blocks interaction; onClick belongs to the caller.",+ code: '<Button variant="destructive" size="sm" onClick={removeItem}>Remove</Button>' },+ { title: "Input · 输入框", files: ["input"], Preview: Inputs,+ description: "Text entry and the shared search-field variant.", options: "Use Input for regular fields and SearchInput for search. Supply a label and describe invalid input.",+ code: '<Input aria-label="Project name" value={name} onChange={event => setName(event.target.value)} />' },+ { title: "Textarea · 多行输入", files: ["textarea"], Preview: Textareas,+ description: "Multiline text using the shared focus treatment.", options: "Accepts native textarea props: value, onChange, rows and disabled.", code: '<Textarea aria-label="Notes" value={notes} onChange={event => setNotes(event.target.value)} />' },+ { title: "ToggleButton · 开关", files: ["toggle-button"], Preview: Switches,+ description: "A controlled on/off switch shared by settings, workspaces and channels.", options: "The caller owns checked and onChange. label supplies its accessible name.", code: '<ToggleButton checked={enabled} onChange={setEnabled} label="Enable feature" />' },+ { title: "Select · 选择器", files: ["select"], Preview: Selects,+ description: "A single choice with keyboard navigation and disabled options.", options: "Compose Select, SelectTrigger, SelectValue, SelectContent and SelectItem. The root owns value/onValueChange.",+ code: '<Select value={value} onValueChange={setValue}>\n <SelectTrigger aria-label="Model"><SelectValue /></SelectTrigger>\n <SelectContent><SelectItem value="default">Default</SelectItem></SelectContent>\n</Select>' },+ { title: "SegmentedControl · 分段选择", files: ["segmented-control"], Preview: Segments,+ description: "A short, always-visible set of choices.", options: 'value, options and onChange are controlled. mode="tabs" adds arrow-key tab navigation.',+ code: '<SegmentedControl value={period} onChange={setPeriod} options={[{ value: "day", label: "Day" }, { value: "week", label: "Week" }]} ariaLabel="Period" />' },+ { title: "Combobox · 搜索选择", files: ["combobox"], Preview: Comboboxes,+ description: "Searchable options with shared keyboard and pointer navigation.", options: "useComboboxNavigation supplies input/list/option props; the caller filters values and owns selection.",+ code: 'const nav = useComboboxNavigation({ open, values, selectedValue, onSelect, onClose });\n<Input {...nav.inputProps} aria-label="Search" />\n<div {...nav.listProps}>\n {values.map(value => <ComboboxOption key={value} {...nav.getOptionProps(value)}>{value}</ComboboxOption>)}\n</div>' },+ { title: "ControlChevron · 控件箭头", files: ["control-chevron"], Preview: () => <ControlChevron />,+ description: "The shared chevron used by selection controls.", options: "className may adjust placement. The icon is decorative; the owning control supplies its accessible name.", code: '<ControlChevron />' },+ { title: "Dialog · 对话框", files: ["dialog"], Preview: Dialogs,+ description: "A modal editor with staged changes, nested selection and focus return.", options: "The caller owns open/onOpenChange and draft/save behavior. Always provide DialogTitle and a description when useful.",+ code: '<Dialog open={open} onOpenChange={setOpen}>\n <DialogTrigger asChild><Button>Edit</Button></DialogTrigger>\n <DialogContent><DialogTitle>Edit item</DialogTitle><DialogDescription>Update this item.</DialogDescription>{editor}</DialogContent>\n</Dialog>' },+ { title: "AlertDialog · 确认对话框", files: ["alert-dialog"], Preview: Alerts,+ description: "An explicit confirmation with separate cancel and action controls.", options: "Compose title, description and footer; perform the action in AlertDialogAction's handler.",+ code: '<Button onClick={() => setOpen(true)}>Remove</Button>\n<AlertDialog open={open} onOpenChange={setOpen}>\n <AlertDialogContent><AlertDialogTitle>Remove item?</AlertDialogTitle><AlertDialogDescription>This removes the item.</AlertDialogDescription><AlertDialogCancel>Cancel</AlertDialogCancel><AlertDialogAction onClick={removeItem}>Remove</AlertDialogAction></AlertDialogContent>\n</AlertDialog>' },+ { title: "Sheet · 侧边面板", files: ["sheet"], Preview: Sheets,+ description: "A modal panel attached to an edge of the viewport.", options: "SheetContent supports side. Include SheetTitle and SheetDescription.",+ code: '<Sheet><SheetTrigger asChild><Button>Details</Button></SheetTrigger><SheetContent side="right"><SheetTitle>Details</SheetTitle><SheetDescription>Additional information.</SheetDescription>{content}</SheetContent></Sheet>' },+ { title: "Popover · 浮层", files: ["popover"], Preview: Popovers,+ description: "A small interactive surface anchored to its trigger.", options: "Compose trigger and content; open/onOpenChange can be controlled. Content follows the owning dialog's portal.",+ code: '<Popover><PopoverTrigger asChild><Button>Note</Button></PopoverTrigger><PopoverContent>{editor}</PopoverContent></Popover>' },+ { title: "DropdownMenu · 菜单", files: ["dropdown-menu"], Preview: Menus,+ description: "Actions, radio choices, nested menus and disabled entries.", options: "Use onSelect for actions and a radio group for a persistent choice.",+ code: '<DropdownMenu><DropdownMenuTrigger asChild><Button>Actions</Button></DropdownMenuTrigger><DropdownMenuContent><DropdownMenuItem onSelect={rename}>Rename</DropdownMenuItem></DropdownMenuContent></DropdownMenu>' },+ { title: "Tooltip / HoverHint · 提示", files: ["tooltip", "tooltip-primitives", "hover-hint"], Preview: Tooltips,+ description: "HoverHint composes the shared tooltip primitives; tooltip.tsx is their public import surface.", options: "Use HoverHint for ordinary hints. Keep essential errors visible. Hover and keyboard focus share the product's timing rules.",+ code: '<HoverHint content="Add an attachment"><Button size="icon" aria-label="Add attachment"><Plus /></Button></HoverHint>' },+ { title: "TruncatedTextTooltip · 截断提示", files: ["truncated-text-tooltip"], Preview: TruncatedText,+ description: "Shows a hint only when the measured text is truncated.", options: "Supply text and a constrained width. Add tabIndex when the text itself should receive keyboard focus.",+ code: '<TruncatedTextTooltip text={projectName} tabIndex={0} className="block max-w-48" />' },+ { title: "Disclosure · 折叠内容", files: ["disclosure"], Preview: Disclosures,+ description: "Expandable content that preserves child state while folded.", options: "Disclosure owns expansion; DisclosureContent accepts a controlled open prop for custom triggers.",+ code: '<Disclosure summary="Advanced options"><Input aria-label="Draft" defaultValue="Preserved" /></Disclosure>' },+ { title: "ExpandableText · 文本展开", files: ["expandable-text"], Preview: Expandable,+ description: "A line-limited preview of the same mounted text.", options: "The caller owns expanded. lines sets the collapsed line count; provide an accessible toggle.",+ code: '<ExpandableText expanded={expanded} lines={2} className="text-sm leading-6">{description}</ExpandableText>' },+ { title: "StreamingLabelSheen · 流光文字", files: ["streaming-label-sheen"], Preview: StreamingLabels,+ description: "A shared text animation for active thinking and tool labels.", options: "active controls animation. String or number children supply the glyph overlay; reduced-motion settings are respected.",+ code: '<StreamingLabelSheen active={running}>Working…</StreamingLabelSheen>' },+].map((example) => ({ ...example, files: example.files.map((file) => `${base}${file}.tsx`) }));diff --git a/webui/src/dev/gallery/gallery.css b/webui/src/dev/gallery/gallery.cssnew file mode 100644index 000000000..114d7c9c0--- /dev/null+++ b/webui/src/dev/gallery/gallery.css@@ -0,0 +1,53 @@+.component-gallery {+ display: flex;+ height: 100dvh;+ flex-direction: column;+ background: hsl(var(--background));+}++.gallery-header {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 1rem;+ border-bottom: 1px solid hsl(var(--border));+ padding: 1rem 1.5rem;+}++.gallery-workspace {+ display: grid;+ min-height: 0;+ flex: 1;+ grid-template-columns: 17rem minmax(0, 1fr);+}++.gallery-sidebar {+ display: flex;+ min-height: 0;+ flex-direction: column;+ border-right: 1px solid hsl(var(--border));+ padding: 1rem;+ background: hsl(var(--sidebar));+}++.gallery-source-list { min-height: 0; flex: 1; overflow-y: auto; }+.gallery-main { min-width: 0; overflow-y: auto; padding: 2rem; }+.gallery-preview { min-width: 0; border: 1px solid hsl(var(--border)); border-radius: var(--radius-panel); padding: 1.5rem; }+.gallery-code { overflow: auto; border-radius: var(--radius-control); padding: 1rem; background: hsl(var(--muted)); font-size: 12px; line-height: 1.6; tab-size: 2; }++.gallery-startup-preview .startup-shell { position: relative; height: 100%; }+.gallery-startup-preview .startup-header { display: flex; justify-content: space-between; padding: 5px 13px; }+.gallery-startup-preview .startup-control-shadow { width: 28px; height: 28px; border-radius: 8px; background: rgba(0, 0, 0, .025); }+.gallery-startup-preview .startup-composer { position: absolute; inset-inline: 16px; bottom: max(24px, env(safe-area-inset-bottom)); box-sizing: border-box; max-width: 768px; margin-inline: auto; height: 96px; border-radius: 24px; background: rgba(0, 0, 0, .025); }+.gallery-startup-preview .startup-status { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; }+html.dark .gallery-startup-preview :is(.startup-control-shadow, .startup-composer) { background: rgba(255, 255, 255, .035); }++@media (max-width: 700px) {+ .gallery-header { padding: 0.75rem 1rem; }+ .gallery-workspace { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, min(22rem, 50%)) minmax(0, 1fr); }+ .gallery-sidebar { overflow-y: auto; border-right: 0; border-bottom: 1px solid hsl(var(--border)); padding: 0.75rem 1rem; }+ .gallery-source-list { min-height: 6rem; }+ .gallery-main { padding: 1.25rem 1rem; }+ .gallery-preview { padding: 1rem; }+}diff --git a/webui/src/dev/gallery/generate_channel_fixtures.py b/webui/src/dev/gallery/generate_channel_fixtures.pynew file mode 100644index 000000000..625f789d3--- /dev/null+++ b/webui/src/dev/gallery/generate_channel_fixtures.py@@ -0,0 +1,70 @@+"""Export channel setup contracts for the gateway-free component gallery."""++from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[4]+sys.path.insert(0, str(REPO_ROOT))++def render_fixtures() -> str:+ from nanobot.channels.registry import discover_plugins++ plugins = discover_plugins()+ lines = [+ "// Generated by generate_channel_fixtures.py from channel setup contracts.",+ 'import type { NanobotFeatureInfo } from "@/lib/types";',+ "",+ "export const channelFeatures: Record<string, NanobotFeatureInfo> = {",+ ]+ for directory in sorted((REPO_ROOT / "nanobot/channels").iterdir()):+ entries = [directory / "webui" / name for name in ("index.ts", "index.tsx")]+ if not any(entry.is_file() for entry in entries):+ continue+ plugin = plugins[directory.name]+ assert plugin.setup is not None+ feature = {+ "name": plugin.name,+ "display_name": plugin.display_name,+ "webui": plugin.webui,+ "type": "channel",+ "enabled": False,+ "installed": True,+ "configured": False,+ "ready": False,+ "status": "not_enabled",+ "install_supported": True,+ "requires_restart": False,+ "runtime_status": "stopped",+ "config_values": {},+ "configured_fields": [],+ "setup": plugin.setup.to_public_dict(plugin.name),+ }+ serialized = json.dumps(feature, ensure_ascii=False, separators=(",", ": "))+ lines.append(f" {json.dumps(plugin.name)}: {serialized},")+ lines.extend(["};", ""])+ return "\n".join(lines)+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--check", action="store_true", help="Check the committed snapshot")+ args = parser.parse_args()+ target = Path(__file__).with_name("channel-fixtures.ts")+ content = render_fixtures()+ if args.check:+ if not target.is_file() or target.read_text(encoding="utf-8") != content:+ print("Channel fixtures are stale; run generate_channel_fixtures.py.", file=sys.stderr)+ return 1+ print("Channel setup fixtures match their Python contracts.")+ return 0+ target.write_text(content, encoding="utf-8", newline="\n")+ print(f"Updated {target.name}.")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/webui/src/dev/gallery/inventory-plugin.ts b/webui/src/dev/gallery/inventory-plugin.tsnew file mode 100644index 000000000..932edcf8d--- /dev/null+++ b/webui/src/dev/gallery/inventory-plugin.ts@@ -0,0 +1,131 @@+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import ts from "typescript";+import type { Plugin } from "vite";++import { foundationPath, type ComponentSource } from "./inventory";++function sourceFiles(directory: string): string[] {+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ if (["tests", "dev", "locales"].includes(entry.name)) return [];+ const file = path.join(directory, entry.name);+ return entry.isDirectory() ? sourceFiles(file) : /\.tsx?$/.test(entry.name) ? [file] : [];+ });+}++function groupFor(file: string): string {+ if (file.startsWith("nanobot/channels/")) return `Channels / ${file.split("/")[2]}`;+ if (file.startsWith(foundationPath)) return "Foundations";+ if (file.includes("/settings/shared/")) return "Settings / shared";+ if (file.includes("/settings/")) return "Settings";+ if (file.includes("/thread/")) return "Conversation";+ if (file.includes("/remote/")) return "Hosts";+ if (file.includes("/workbench/")) return "Workbench";+ if (file.includes("/icons/")) return "Icons";+ return "Shared views & shell";+}++/** Index source modules and direct imports without executing application code. */+export function componentInventory(repo: string): ComponentSource[] {+ const frontend = path.join(repo, "webui/src");+ const channels = path.join(repo, "nanobot/channels");+ const channelRoots = readdirSync(channels, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .flatMap((entry) => {+ const directory = path.join(channels, entry.name);+ return readdirSync(directory, { withFileTypes: true })+ .filter((child) => child.isDirectory() && child.name === "webui")+ .map(() => path.join(directory, "webui"));+ });+ const files = [...sourceFiles(frontend), ...channelRoots.flatMap(sourceFiles)];+ const relative = (file: string) => path.relative(repo, file).split(path.sep).join("/");+ const sources = new Map(files.map((file) => [file, ts.createSourceFile(+ file, readFileSync(file, "utf8"), ts.ScriptTarget.Latest, true,+ )]));+ const usedBy = new Map<string, Set<string>>();++ for (const [file, source] of sources) {+ const recordImport = (specifier: string) => {+ const target = specifier.startsWith("@/") ? path.join(frontend, specifier.slice(2))+ : specifier.startsWith(".") ? path.resolve(path.dirname(file), specifier) : undefined;+ if (!target) return;+ const resolved = [target, `${target}.tsx`, `${target}.ts`, path.join(target, "index.tsx"), path.join(target, "index.ts")]+ .find((candidate) => sources.has(candidate));+ if (!resolved) return;+ const consumers = usedBy.get(resolved) ?? new Set<string>();+ consumers.add(relative(file));+ usedBy.set(resolved, consumers);+ };+ const visit = (node: ts.Node) => {+ if ((ts.isImportDeclaration(node) || ts.isExportDeclaration(node))+ && node.moduleSpecifier && ts.isStringLiteral(node.moduleSpecifier)) {+ recordImport(node.moduleSpecifier.text);+ } else if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword+ && node.arguments[0] && ts.isStringLiteral(node.arguments[0])) {+ recordImport(node.arguments[0].text);+ }+ ts.forEachChild(node, visit);+ };+ visit(source);+ }++ return [...sources].filter(([file]) =>+ (file.endsWith(".tsx") && file.startsWith(path.join(frontend, "components") + path.sep))+ || channelRoots.some((root) => file.startsWith(root + path.sep)+ && (file.endsWith(".tsx") || file === path.join(root, "index.ts"))))+ .map(([file, source]) => {+ const names = new Set<string>();+ for (const statement of source.statements) {+ if (ts.isExportAssignment(statement) && !statement.isExportEquals) names.add("default");+ if (ts.isExportDeclaration(statement) && !statement.isTypeOnly+ && statement.exportClause && ts.isNamedExports(statement.exportClause)) {+ for (const item of statement.exportClause.elements) {+ if (!item.isTypeOnly) names.add(item.name.text);+ }+ }+ const modifiers = ts.canHaveModifiers(statement) ? ts.getModifiers(statement) : undefined;+ const exported = modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);+ if (!exported) continue;+ if (modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.DefaultKeyword)) {+ names.add("default");+ continue;+ }+ if (ts.isFunctionDeclaration(statement) && statement.name) names.add(statement.name.text);+ if (ts.isVariableStatement(statement)) {+ for (const declaration of statement.declarationList.declarations) {+ if (ts.isIdentifier(declaration.name)) names.add(declaration.name.text);+ }+ }+ }+ const id = relative(file);+ return {+ path: id,+ name: path.basename(file).replace(/\.tsx?$/, ""),+ group: groupFor(id),+ exports: [...names].sort(),+ usedBy: [...(usedBy.get(file) ?? [])].sort(),+ source: source.text,+ };+ }).sort((a, b) => a.path.localeCompare(b.path));+}++/** Only Vite's development server exposes the source inventory. */+export function componentGallery(repo: string): Plugin {+ return {+ name: "nanobot-component-gallery",+ apply: "serve",+ configureServer(server) {+ server.middlewares.use("/__nanobot_components", (_request, response) => {+ try {+ response.setHeader("Content-Type", "application/json; charset=utf-8");+ response.setHeader("Cache-Control", "no-store");+ response.end(JSON.stringify(componentInventory(repo)));+ } catch (error) {+ server.config.logger.error(String(error));+ response.statusCode = 500;+ response.end("Could not read the component inventory.");+ }+ });+ },+ };+}diff --git a/webui/src/dev/gallery/inventory.ts b/webui/src/dev/gallery/inventory.tsnew file mode 100644index 000000000..64285bc05--- /dev/null+++ b/webui/src/dev/gallery/inventory.ts@@ -0,0 +1,10 @@+export interface ComponentSource {+ path: string;+ name: string;+ group: string;+ exports: string[];+ usedBy: string[];+ source: string;+}++export const foundationPath = "webui/src/components/ui/";diff --git a/webui/src/dev/gallery/main.tsx b/webui/src/dev/gallery/main.tsxnew file mode 100644index 000000000..99fac5791--- /dev/null+++ b/webui/src/dev/gallery/main.tsx@@ -0,0 +1,11 @@+import { createRoot } from "react-dom/client";++import { initializeI18n } from "@/i18n";+import { Gallery } from "./Gallery";+import "@/globals.css";+import "./gallery.css";++const root = document.getElementById("root");+if (!root) throw new Error("Gallery root element missing");++void initializeI18n().then(() => createRoot(root).render(<Gallery />));diff --git a/webui/src/dev/gallery/providers.tsx b/webui/src/dev/gallery/providers.tsxnew file mode 100644index 000000000..5db4bc05a--- /dev/null+++ b/webui/src/dev/gallery/providers.tsx@@ -0,0 +1,151 @@+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";++import { ProvidersSettings, type ProviderSettingsEntry } from "@/components/settings/models/ProviderSettings";+import { parseProviderObject, providerFormFromRow, type CustomProviderDraft, type ProviderForm } from "@/components/settings/models/providerForm";+import { Button } from "@/components/ui/button";+import type { SettingsPayload } from "@/lib/types";+import type { ComponentExample } from "./example";+import { settings } from "./settings";++type ProviderRow = SettingsPayload["providers"][number];++const previewProviders: ProviderRow[] = [+ { name: "custom", label: "Custom", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.example.com/v1" },+ { name: "anthropic", label: "Anthropic", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.anthropic.com", request_apis: ["anthropic_messages"] },+ { name: "openai_codex", label: "OpenAI Codex", configured: true, auth_type: "oauth", api_key_required: false, oauth_login_supported: true, advanced_fields: ["proxy", "extra_body"] },+ { name: "xai_grok", label: "xAI Grok", configured: true, auth_type: "oauth", api_key_required: false, oauth_login_supported: true, advanced_fields: ["proxy", "extra_body"] },+ { name: "deepseek", label: "DeepSeek", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.deepseek.com" },+ { name: "zhipu", label: "Zhipu AI", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://open.bigmodel.cn/api/paas/v4" },+ { name: "minimax", label: "MiniMax", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.minimax.io/v1" },+ { name: "groq", label: "Groq", configured: true, auth_type: "api_key", api_key_hint: "••••••••", api_base: "https://api.groq.com/openai/v1" },+ { name: "openai", label: "OpenAI", configured: false, auth_type: "api_key", default_api_base: "https://api.openai.com/v1", request_apis: ["responses", "chat_completions"], provider_api_configurable: true, model_api_configurable: true },+ { name: "ollama", label: "Ollama", configured: false, auth_type: "api_key", api_key_required: false, default_api_base: "http://localhost:11434/v1", model_catalog: "local" },+];++function stringParameters(value: string): Record<string, string> | null {+ const parsed = parseProviderObject(value);+ if (!parsed) return null;+ const result: Record<string, string> = {};+ for (const [key, entry] of Object.entries(parsed)) {+ if (typeof entry !== "string") return null;+ result[key] = entry;+ }+ return result;+}++function providerValues(form: ProviderForm) {+ const extraHeaders = stringParameters(form.extraHeaders);+ const extraQuery = stringParameters(form.extraQuery);+ const extraBody = parseProviderObject(form.extraBody);+ if (!extraHeaders || !extraQuery || !extraBody) return null;+ return {+ api_base: form.apiBase.trim() || null,+ api: form.api,+ api_key_hint: form.apiKey.trim() ? "••••••••" : undefined,+ proxy: form.proxy.trim() || null,+ extra_headers: extraHeaders,+ extra_query: extraQuery,+ extra_body: extraBody,+ thinking_style: form.thinkingStyle.trim() || null,+ region: form.region.trim() || null,+ profile: form.profile.trim() || null,+ };+}++function ProvidersPreview() {+ const { t } = useTranslation();+ const [payload, setPayload] = useState<SettingsPayload>(() => ({+ ...settings, providers: previewProviders, provider_api_configuration_supported: true,+ }));+ const [drafts, setDrafts] = useState<Record<string, ProviderForm>>(() =>+ Object.fromEntries(previewProviders.map((provider) => [provider.name, providerFormFromRow(provider)])));+ const [visibleKeys, setVisibleKeys] = useState<Record<string, boolean>>({});+ const [editingKeys, setEditingKeys] = useState<Record<string, boolean>>({});+ const [entry, setEntry] = useState<ProviderSettingsEntry | null>(null);+ const [showBrandLogos, setShowBrandLogos] = useState(true);+ const [notice, setNotice] = useState("");+ const trigger = useRef<HTMLButtonElement | null>(null);+ const nextCustomId = useRef(1);+ const providerRows: Record<string, ProviderRow> = Object.fromEntries(payload.providers.map((provider) => [provider.name, provider]));++ const resetDraft = (name: string) => {+ setDrafts((current) => ({ ...current, [name]: providerFormFromRow(providerRows[name]) }));+ setVisibleKeys((current) => ({ ...current, [name]: false }));+ setEditingKeys((current) => ({ ...current, [name]: false }));+ };+ const saveProvider = async (name: string) => {+ const form = drafts[name];+ const values = providerValues(form);+ if (!values) {+ setNotice("请输入有效的请求参数 JSON;请求头和查询参数的值须为字符串。");+ return false;+ }+ setPayload((current) => ({ ...current, providers: current.providers.map((provider) => provider.name === name+ ? { ...provider, ...values, api_key_hint: values.api_key_hint ?? provider.api_key_hint,+ label: provider.is_custom ? form.displayName.trim() : provider.label, configured: true }+ : provider) }));+ setDrafts((current) => ({ ...current, [name]: { ...form, apiKey: "" } }));+ setEditingKeys((current) => ({ ...current, [name]: false }));+ setNotice(`已保存 ${providerRows[name].label} 的预览配置`);+ return true;+ };+ const createCustomProvider = async (form: CustomProviderDraft) => {+ const values = providerValues(form);+ if (!values) {+ setNotice("请输入有效的请求参数 JSON;请求头和查询参数的值须为字符串。");+ return null;+ }+ const name = `custom_preview_${nextCustomId.current++}`;+ const row: ProviderRow = { ...values, name, label: form.name.trim(), is_custom: true,+ configured: true, auth_type: "api_key", api_key_required: false, provider_api_configurable: true,+ advanced_fields: ["extra_headers", "extra_body", "extra_query", "proxy", "thinking_style"] };+ const next: SettingsPayload = { ...payload, providers: [...payload.providers, row], created_provider: name };+ setPayload(next);+ setDrafts((current) => ({ ...current, [name]: providerFormFromRow(row) }));+ setNotice(`已添加 ${row.label}`);+ return next;+ };+ const changeOAuth = (name: string, configured: boolean) => {+ setPayload((current) => ({ ...current, providers: current.providers.map((provider) => provider.name === name+ ? { ...provider, configured } : provider) }));+ setNotice(configured ? "预览授权状态已设为已登录" : "预览授权状态已设为未登录");+ };++ return <div className="space-y-4">+ <div className="flex flex-wrap gap-3">+ <Button variant="outline" onClick={(event) => {+ trigger.current = event.currentTarget;+ setEntry({ kind: "manage" });+ }}>{t("settings.providers.manageProviders")}</Button>+ <Button variant="outline" onClick={(event) => {+ trigger.current = event.currentTarget;+ setEntry({ kind: "add" });+ }}>{t("settings.providers.addProvider")}</Button>+ <Button variant="ghost" aria-pressed={showBrandLogos} onClick={() => setShowBrandLogos((current) => !current)}>+ {showBrandLogos ? "使用内置图标" : "使用品牌图标"}+ </Button>+ </div>+ <p role="status" className="text-xs text-muted-foreground">+ {notice || `${payload.providers.filter((provider) => provider.configured).length} 个已配置提供商`}+ </p>+ {entry ? <ProvidersSettings entry={entry} settings={payload} showBrandLogos={showBrandLogos}+ onClose={() => setEntry(null)} onCloseAutoFocus={(event) => { event.preventDefault(); trigger.current?.focus(); }}+ onProviderAdded={() => setNotice("已添加提供商")}+ nanobotFeatures={null} featureAction={null} capabilityError={null} providerForms={drafts}+ visibleProviderKeys={visibleKeys} editingProviderKeys={editingKeys} providerSaving={null} remoteBrowserAccess={false}+ onResetProviderDraft={resetDraft}+ onToggleProviderKey={(name) => setVisibleKeys((current) => ({ ...current, [name]: !current[name] }))}+ onToggleProviderKeyEditing={(name) => setEditingKeys((current) => ({ ...current, [name]: !current[name] }))}+ onChangeProviderForm={(name, values) => setDrafts((current) => ({ ...current, [name]: { ...current[name], ...values } }))}+ onSaveProvider={saveProvider} onCreateCustomProvider={createCustomProvider}+ onProviderOAuthLogin={(name) => changeOAuth(name, true)} onProviderOAuthLogout={(name) => changeOAuth(name, false)} /> : null}+ </div>;+}++export const providerExamples: ComponentExample[] = [+ { title: "ProvidersSettings · 管理提供商", files: ["webui/src/components/settings/models/ProviderSettings.tsx"], Preview: ProvidersPreview,+ description: "查看真实提供商管理弹窗与添加流程。",+ options: "复用设置中的 ProvidersSettings。目录、表单与保存回调由调用方控制;此处修改本地示例数据,支持配置、搜索、创建与取消。",+ code: '<ProvidersSettings entry={{ kind: "manage" }} settings={settings} providerForms={drafts} showBrandLogos={true} onSaveProvider={save} onCreateCustomProvider={create} {...callbacks} />' },+];diff --git a/webui/src/dev/gallery/remote.tsx b/webui/src/dev/gallery/remote.tsxnew file mode 100644index 000000000..2a7f51d36--- /dev/null+++ b/webui/src/dev/gallery/remote.tsx@@ -0,0 +1,137 @@+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";++import { PairRouteSettingsView } from "@/components/remote/PairRouteSettingsView";+import { QuickPairSetupView, type PairConnectionPreview, type QuickPairSetupState } from "@/components/remote/QuickPairSetupView";+import { SSHHostPickerView } from "@/components/remote/SSHHostPickerView";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent } from "@/components/ui/dialog";+import { copyTextToClipboard } from "@/lib/clipboard";+import type { SSHDiscovery } from "@/lib/remote-instances";+import { StatePicker, type ComponentExample } from "./example";+import "@/components/remote/remote-layout.css";++const routes = [{ id: "gallery-ssh", name: "开发 SSH 路由" }, { id: "gallery-vpn", name: "VPN 路由" }];+type RouteStory = "direct" | "saved_route" | "saving" | "save_error" | "refresh_error";++function RouteEditor({ story }: { story: RouteStory }) {+ const { t } = useTranslation();+ const initial = story === "saved_route" ? "saved" : story === "direct" ? "direct" : "gallery-ssh";+ const [route, setRoute] = useState(initial);+ const [original, setOriginal] = useState(story === "saving" || story === "save_error" ? "direct" : initial);+ const [saved, setSaved] = useState(story === "refresh_error");+ const [error, setError] = useState(story === "save_error" ? t("remote.errors.pair_route_mismatch")+ : story === "refresh_error" ? t("remote.errors.directory_unavailable") : "");+ return <PairRouteSettingsView hasSavedRoute={story === "saved_route"} routes={routes}+ route={route} original={original} busy={story === "saving"} error={error} saved={saved}+ onRouteChange={(next) => { setRoute(next); setError(""); setSaved(false); }}+ onSave={() => { setOriginal(route); setSaved(true); setError(""); }} />;+}++function PairRoutePreview() {+ const [story, setStory] = useState<RouteStory>("direct");+ return <>+ <StatePicker label="路由状态" value={story} options={["direct", "saved_route", "saving", "save_error", "refresh_error"]} onChange={setStory} />+ <RouteEditor key={story} story={story} />+ </>;+}++const preview: PairConnectionPreview = {+ id: "gallery-invitation", host: "[email protected]", hostname: "开发主机",+ fingerprint: "SHA256:gallery-example-fingerprint", authorized_until: Date.UTC(2026, 10, 1) / 1000,+ revoke_command: "nanobot remote revoke gallery-authorization",+};+type PairStory = "invite" | "copied" | "manual" | "confirm" | "existing" | "saved_retry" | "waiting" | "expired";++function pairState(story: PairStory): QuickPairSetupState {+ return {+ request: story === "waiting" ? null : {+ id: "gallery-invitation", command: "nanobot remote pair nbpr1.gallery-example", expires: Date.now() / 1000 + (story === "expired" ? -60 : 600),+ },+ preview: story === "confirm" || story === "saved_retry" ? preview : story === "existing" ? {+ ...preview, existing_connection: { id: "gallery-host", name: "团队主机", connected: true },+ } : null,+ code: ["manual", "confirm", "existing", "saved_retry"].includes(story) ? "nbpc1.gallery-example" : "",+ saved: story === "saved_retry", busy: false, busyVisible: story === "waiting",+ error: story === "saved_retry" ? "remote.errors.ssh_connection_closed" : "",+ status: story === "waiting" ? "connecting" : "open", copied: story === "copied", expired: story === "expired",+ manual: ["manual", "confirm", "existing", "saved_retry"].includes(story), panel: null, returned: false,+ };+}++function QuickPairPreview() {+ const [story, setStory] = useState<PairStory>("invite");+ const [state, setState] = useState(() => pairState("invite"));+ const [open, setOpen] = useState(false);+ const [feedback, setFeedback] = useState("");+ return <div className="space-y-4">+ <StatePicker label="配对阶段" value={story} options={["invite", "copied", "manual", "confirm", "existing", "saved_retry", "waiting", "expired"]}+ onChange={(next) => { setStory(next); setState(pairState(next)); setFeedback(""); }} />+ <Button variant="outline" onClick={() => setOpen(true)}>打开快速配对</Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent className="remote-dialog max-w-sm">+ <QuickPairSetupView state={state} routeSettings={<RouteEditor story="saved_route" />}+ onStart={() => { setState(pairState("invite")); setStory("invite"); }}+ onReview={() => setState((current) => ({ ...current, preview, error: "" }))}+ onConnect={() => { setFeedback("已选择连接:开发主机。"); setOpen(false); }}+ onCopyCommand={() => {+ if (!state.request) return;+ void copyTextToClipboard(state.request.command).then((copied) => setState((current) => ({+ ...current, copied, panel: copied ? null : "command", error: copied ? "" : "remote.pair.copyFailed",+ })));+ }}+ onCodeChange={(code) => setState((current) => ({ ...current, code, error: "" }))}+ onManualChange={(manual) => setState((current) => ({ ...current, manual, panel: null, error: "" }))}+ onPanelChange={(panel) => setState((current) => ({ ...current, panel }))}+ onBack={() => setState((current) => ({ ...current, preview: null, error: "", manual: current.manual || !current.request?.command }))}+ onCancel={() => setOpen(false)} onSSH={() => { setFeedback("已选择 SSH 连接方式。"); setOpen(false); }} />+ </DialogContent>+ </Dialog>+ <p role="status" className="text-xs text-muted-foreground">{feedback || "示例邀请与回执仅用于展示;确认动作更新本地反馈。"}</p>+ </div>;+}++const discovery: SSHDiscovery = {+ hosts: [+ { host: "dev", source: "~/.ssh/config", ssh_config: "~/.ssh/config" },+ { host: "team-staging", source: "~/.ssh/team.conf", ssh_config: "~/.ssh/config" },+ { host: "team-production", source: "~/.ssh/team.conf", ssh_config: "~/.ssh/config" },+ ],+ files: ["~/.ssh/config", "~/.ssh/team.conf"], incomplete: false,+};+type SSHStory = "ready" | "custom_config" | "imported" | "loading" | "error" | "partial" | "address_only";++function SSHHostPreview() {+ const { t } = useTranslation();+ const [story, setStory] = useState<SSHStory>("ready");+ const [value, setValue] = useState("");+ const [feedback, setFeedback] = useState("");+ const input = useRef<HTMLInputElement>(null);+ return <div className="space-y-4">+ <StatePicker label="SSH 地址状态" value={story} options={["ready", "custom_config", "imported", "loading", "error", "partial", "address_only"]}+ onChange={(next) => { setStory(next); setValue(next === "custom_config" ? "[email protected]" : next === "imported" ? "dev" : ""); setFeedback(""); }} />+ <SSHHostPickerView disabled={false} value={value} imported={story === "imported"}+ suggestions={story !== "address_only"} customConfig={story === "custom_config"}+ discovery={story === "error" ? null : story === "partial" ? { ...discovery, incomplete: true } : discovery}+ busy={story === "loading"} error={story === "error" ? t("remote.discoveryError") : ""}+ onRefresh={() => { setStory("ready"); setFeedback("已刷新示例地址。"); }}+ onChange={setValue} onBlur={() => setFeedback(value ? `已输入:${value}` : "")}+ inputRef={input} />+ <p role="status" className="text-xs text-muted-foreground">{feedback || "输入内容筛选地址;按方向键选择 SSH 别名。"}</p>+ </div>;+}++export const remoteExamples: ComponentExample[] = [+ { title: "PairRouteSettingsView · 配对路由", files: ["webui/src/components/remote/PairRouteSettingsView.tsx"], Preview: PairRoutePreview,+ description: "切换已存路由、保存、出错和刷新失败状态,选择路由后在本地保存。",+ options: "route 与 original 由调用方管理;routes 提供 SSH 路由。保存成功与目录刷新失败分别呈现,画廊与实际设置使用同一个视图。",+ code: '<PairRouteSettingsView hasSavedRoute={hasSavedRoute} routes={routes} route={route} original={original} busy={busy} error={error} saved={saved} onRouteChange={setRoute} onSave={save} />' },+ { title: "QuickPairSetupView · 快速配对", files: ["webui/src/components/remote/QuickPairSetupView.tsx"], Preview: QuickPairPreview,+ description: "体验邀请复制、回执输入、访问确认、已有主机和保存后重试界面。",+ options: "state 提供当前配对结果与显示状态,回调交给所属界面执行动作,routeSettings 组合路由设置。画廊使用示例数据和本地回调;实际配对由 QuickPairSetup 管理。",+ code: '<QuickPairSetupView state={state} routeSettings={routeSettings} onStart={start} onReview={review} onConnect={connect} onCopyCommand={copy} onCodeChange={setCode} onManualChange={setManual} onPanelChange={setPanel} onBack={back} onCancel={cancel} onSSH={showSSH} />' },+ { title: "SSHHostPickerView · SSH 地址", files: ["webui/src/components/remote/SSHHostPickerView.tsx"], Preview: SSHHostPreview,+ description: "筛选 SSH 别名,使用方向键选择,查看导入、读取和错误状态。",+ options: "discovery 提供当前配置文件的地址;value、busy、error 与回调由调用方控制。customConfig 保留自定义配置的别名发现行为,inputRef 用于选择后的焦点。",+ code: '<SSHHostPickerView disabled={false} value={host} imported={false} discovery={discovery} busy={busy} error={error} onRefresh={refresh} onChange={setHost} onBlur={validateHost} inputRef={hostInput} />' },+];diff --git a/webui/src/dev/gallery/runtime-settings.tsx b/webui/src/dev/gallery/runtime-settings.tsxnew file mode 100644index 000000000..d91b740a1--- /dev/null+++ b/webui/src/dev/gallery/runtime-settings.tsx@@ -0,0 +1,122 @@+import { useRef, useState } from "react";++import { StarLinkView, StarPromptView } from "@/components/StarPromptView";+import { AboutSettingsView } from "@/components/settings/overview/AboutSettingsView";+import { AppearanceSettingsView } from "@/components/settings/overview/AppearanceSettingsView";+import { VersionCheckRowView, type VersionCheckState } from "@/components/settings/overview/VersionCheckRowView";+import { AutomationChatBindingView } from "@/components/settings/system/AutomationChatBindingView";+import { AutomationRunDialogView, type AutomationRunResult } from "@/components/settings/system/AutomationRunDialogView";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";+import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";+import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";+import { StatePicker, type ComponentExample } from "./example";++const job: SessionAutomationJob = {+ id: "gallery-report", name: "Weekly summary", enabled: true, chat_binding_revision: "gallery-1",+ schedule: { kind: "cron", expr: "30 9 * * 1", tz: "UTC" },+ payload: { message: "Summarize the changes and open questions." }, state: {},+ origin: { channel: "websocket", title: "Planning" },+};+const chats: AutomationChatsPayload = {+ revision: "gallery-1", current: { id: "planning", title: "Planning", channel: "websocket" },+ chats: [{ id: "planning", title: "Planning", channel: "websocket" },+ { id: "reviews", title: "Reviews", channel: "websocket" },+ { id: "archived", title: "Archived chat", channel: "websocket", unavailable: true }],+};++function RunResultPreview() {+ const [mode, setMode] = useState<"complete" | "loading" | "error" | "empty" | "unavailable">("complete");+ const [open, setOpen] = useState(false);+ const trigger = useRef<HTMLButtonElement>(null);+ const result: AutomationRunResult = mode === "loading" || mode === "error"+ ? { status: mode, response: null }+ : { status: "loaded", response: mode === "empty" ? "" : mode === "unavailable" ? null : "## Weekly summary\n\n- **Completed:** component previews\n- **Next:** review the changes" };+ return <><StatePicker label="运行结果" value={mode} options={["complete", "loading", "error", "empty", "unavailable"]} onChange={setMode} />+ <Button ref={trigger} variant="outline" onClick={() => setOpen(true)}>查看运行结果</Button>+ <AutomationRunDialogView job={job} run={{ run_at_ms: Date.UTC(2026, 9, 12, 9, 30), status: "ok", duration_ms: 3200 }}+ locale="zh-CN" open={open} result={result} onRetry={() => setMode("complete")} onOpenChange={setOpen}+ onCloseAutoFocus={(event) => { event.preventDefault(); trigger.current?.focus(); }} /></>;+}++function ChatBindingPreview() {+ const [mode, setMode] = useState<"ready" | "pending" | "load-error" | "conflict">("ready");+ const [task, setTask] = useState(job);+ const [data, setData] = useState(chats);+ const [notice, setNotice] = useState("");+ return <><StatePicker label="聊天绑定状态" value={mode} options={["ready", "pending", "load-error", "conflict"]} onChange={setMode} />+ <Dialog><DialogTrigger asChild><Button variant="outline">设置运行聊天</Button></DialogTrigger>+ <DialogContent aria-describedby={undefined} className="max-w-[520px] gap-0 p-0">+ <AutomationChatBindingView job={mode === "pending" ? { ...task, state: { pending: true } } : task}+ data={data} loadError={mode === "load-error"} showBrandLogos={false} onReload={() => setMode("ready")}+ onSave={async (_task, values) => {+ if (mode === "conflict") throw new Error("automation_chat_conflict");+ setTask((current) => ({ ...current, chat_binding_revision: `${current.chat_binding_revision}-next`, payload: { ...current.payload, message: values.message } }));+ }} onSaved={(target) => {+ setData((current) => ({ ...current, current: target, revision: `${current.revision}-next` }));+ setNotice(`下次运行将在 ${target.title} 中进行`);+ }}>{(picker) => <>+ <DialogHeader className="px-6 pb-4 pr-12 pt-5"><DialogTitle>{task.name}</DialogTitle></DialogHeader>+ <div className="px-6 pb-6">{picker}</div>+ </>}</AutomationChatBindingView>+ </DialogContent>+ </Dialog><p role="status" className="mt-4 text-xs text-muted-foreground">{notice || "选择目标聊天,确认或修改任务说明。"}</p></>;+}++function AboutPreview() {+ const [mode, setMode] = useState<"ready" | "checking" | "up-to-date" | "update" | "error">("ready");+ const [notice, setNotice] = useState("");+ const result: VersionCheckState = mode === "up-to-date" ? { type: mode }+ : mode === "update" ? { type: mode, latestVersion: "0.3.6", pypiUrl: "https://pypi.org/project/nanobot-ai/" }+ : mode === "error" ? { type: mode, message: "无法获取版本信息,请重试。" } : null;+ return <><StatePicker label="版本状态" value={mode} options={["ready", "checking", "up-to-date", "update", "error"]} onChange={setMode} />+ <AboutSettingsView reportIssueUrl="https://github.com/HKUDS/nanobot/issues/new?template=bug_report.yml"+ versionCheck={<VersionCheckRowView currentVersion="0.3.5" currentCommit="abcdef1234567890" checking={mode === "checking"}+ result={result} onCheck={() => setMode("update")} />}+ starLink={<StarLinkView onActivate={() => setNotice("选择了 GitHub 链接")} />} />+ {notice ? <p role="status" className="mt-4 text-xs text-muted-foreground">{notice}</p> : null}</>;+}++function AppearancePreview() {+ const [theme, setTheme] = useState<"light" | "dark">("light");+ const [preferences, setPreferences] = useState(DEFAULT_LOCAL_PREFS);+ return <><AppearanceSettingsView theme={theme} onToggleTheme={() => setTheme((current) => current === "light" ? "dark" : "light")}+ localPrefs={preferences} onChangeLocalPrefs={setPreferences}+ onChangeBrowserNotifications={(enabled) => setPreferences((current) => ({ ...current, browserNotifications: enabled }))} />+ <pre role="status" className="mt-4 overflow-auto rounded-control bg-muted p-4 text-xs">{JSON.stringify({ theme, ...preferences }, null, 2)}</pre></>;+}++function StarInvitationPreview() {+ const [mode, setMode] = useState<"ready" | "saving" | "error">("ready");+ const [open, setOpen] = useState(false);+ const [notice, setNotice] = useState("");+ return <><StatePicker label="邀请状态" value={mode} options={["ready", "saving", "error"]} onChange={setMode} />+ <Button variant="outline" onClick={() => setOpen(true)}>查看邀请</Button>+ <StarPromptView open={open} saving={mode === "saving"} error={mode === "error"} onOpenChange={setOpen}+ onDismissForever={() => { setNotice("预览中选择了不再提醒"); setOpen(false); }}+ onStar={() => { setNotice("预览中选择了 GitHub 链接"); setOpen(false); }} />+ {notice ? <p role="status" className="mt-4 text-xs text-muted-foreground">{notice}</p> : null}</>;+}++export const runtimeSettingsExamples: ComponentExample[] = [+ { title: "AutomationRunDialogView · 运行结果", files: ["webui/src/components/settings/system/AutomationRunDialogView.tsx"], Preview: RunResultPreview,+ description: "打开运行结果,比较 Markdown 回复、加载、重试、空回复与历史记录缺失状态。",+ options: "result 提供加载状态与已取得的回复。onRetry 交给调用方处理;此视图不读取运行时或请求结果。",+ code: '<AutomationRunDialogView job={job} run={run} locale="zh-CN" open={open} result={{ status: "loaded", response }} onRetry={retry} onOpenChange={setOpen} onCloseAutoFocus={restoreFocus} />' },+ { title: "AutomationChatBindingView · 运行聊天", files: ["webui/src/components/settings/system/AutomationChatBindingView.tsx"], Preview: ChatBindingPreview,+ description: "选择运行聊天、修改任务说明,确认、更换回来或取消;可比较任务占用、加载错误与冲突。",+ options: "data 与 job 提供可用聊天和绑定版本。视图管理确认草稿;onSave、onSaved 与 onReload 由功能入口接入数据操作。",+ code: '<AutomationChatBindingView job={job} data={chats} loadError={false} showBrandLogos={false} onSave={save} onSaved={updateCurrent} onReload={reload}>{renderDetails}</AutomationChatBindingView>' },+ { title: "About and version views · 关于与版本", files: ["webui/src/components/settings/overview/AboutSettingsView.tsx", "webui/src/components/settings/overview/VersionCheckRowView.tsx"], Preview: AboutPreview,+ description: "比较版本检查状态、提交链接、更新入口和关于页面;按钮用示例结果更新显示。",+ options: "AboutSettingsView 接受版本与支持链接的组合。VersionCheckRowView 展示 checking/result,并通过 onCheck 请求检查。真实检查与诊断链接数据由功能入口负责。",+ code: '<AboutSettingsView reportIssueUrl={reportIssueUrl} versionCheck={<VersionCheckRowView currentVersion={version} checking={checking} result={result} onCheck={check} />} starLink={<StarLinkView onActivate={star} />} />' },+ { title: "AppearanceSettingsView · 外观选项", files: ["webui/src/components/settings/overview/AppearanceSettingsView.tsx"], Preview: AppearancePreview,+ description: "切换外观、活动展示、文件差异和通知偏好,下方显示示例值。",+ options: "主题和偏好由调用方管理。onChangeBrowserNotifications 将权限申请交给功能入口;预览回调只改变示例开关。",+ code: '<AppearanceSettingsView theme={theme} onToggleTheme={toggleTheme} localPrefs={preferences} onChangeLocalPrefs={setPreferences} onChangeBrowserNotifications={changeNotifications} />' },+ { title: "StarPromptView · 支持邀请", files: ["webui/src/components/StarPromptView.tsx"], Preview: StarInvitationPreview,+ description: "打开实际邀请弹窗,比较保存与错误状态,体验暂缓、GitHub 链接和不再提醒的操作。",+ options: "open、saving 和 error 是显示状态。领取邀请与持久化偏好由原有 StarPrompt 入口负责;视图只调用传入操作。",+ code: '<StarPromptView open={open} saving={saving} error={error} onOpenChange={setOpen} onDismissForever={dismiss} onStar={openRepository} />' },+];diff --git a/webui/src/dev/gallery/settings.tsx b/webui/src/dev/gallery/settings.tsxnew file mode 100644index 000000000..64514dcae--- /dev/null+++ b/webui/src/dev/gallery/settings.tsx@@ -0,0 +1,430 @@+import { useMemo, useState } from "react";++import { AdvancedSettings, networkSafetyFormFromPayload } from "@/components/settings/capabilities/SecuritySettings";+import { ImageGenerationSettings, imageGenerationFormFromPayload } from "@/components/settings/capabilities/ImageGenerationSettings";+import { TranscriptionSettings, transcriptionFormFromPayload } from "@/components/settings/capabilities/TranscriptionSettings";+import { WebSettings, webSearchDraftState, webSearchFormFromPayload } from "@/components/settings/capabilities/WebSettings";+import { ChannelCatalogRow } from "@/components/settings/channels/ChannelCatalogRow";+import { ChannelFieldGroups, channelRequirementErrors } from "@/components/settings/channels/ChannelCredentialFields";+import { ChannelHelpMenu } from "@/components/settings/channels/ChannelHelpMenu";+import { ChannelLogo, ChannelRuntimeError, ChannelStatusBadge } from "@/components/settings/channels/ChannelIdentity";+import { ChannelProviderPresets, ChannelSetupActions } from "@/components/settings/channels/ChannelSetupParts";+import { ChannelValidationProgress } from "@/components/settings/channels/ChannelValidationProgress";+import type { ChannelConfigField, ChannelProviderPreset } from "@/channel-plugins/catalog";+import type { SettingsSectionKey } from "@/components/settings/contracts";+import { ModelAPIControl } from "@/components/settings/models/ModelAPIControl";+import { ProviderAPIControl } from "@/components/settings/models/ProviderAPIControl";+import { ProviderParameterFields, type RequestParameterDraft } from "@/components/settings/models/ProviderParameterFields";+import { ProviderSearchList } from "@/components/settings/models/ProviderSearchList";+import { ReasoningEffortPicker } from "@/components/settings/models/ReasoningEffortPicker";+import { OverviewSettings } from "@/components/settings/overview/OverviewSettings";+import { SettingsSidebar } from "@/components/settings/SettingsSidebar";+import { CatalogSkeleton } from "@/components/settings/shared/CatalogSkeleton";+import { ModelIdPicker, ProviderPicker, ProviderPickerIcon } from "@/components/settings/shared/ModelControls";+import { ProviderIcon } from "@/components/settings/shared/ProviderIcon";+import { RemoveActionButton } from "@/components/settings/shared/RemoveActionButton";+import { SettingsGroup, SettingsRow } from "@/components/settings/shared/SettingsControls";+import { SettingsHint } from "@/components/settings/shared/SettingsHint";+import { SettingsTextEditor } from "@/components/settings/shared/SettingsTextEditor";+import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";+import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";+import { AutomationCalendar } from "@/components/settings/system/AutomationCalendar";+import { AutomationRunDialogView } from "@/components/settings/system/AutomationRunDialogView";+import { AutomationRunAtPicker } from "@/components/settings/system/AutomationRunAtPicker";+import { TokenUsageCard } from "@/components/settings/TokenUsageCard";+import { Button } from "@/components/ui/button";+import type { ChannelValidationPayload, ModelAPIConfig, NanobotFeatureInfo, SessionAutomationJob, SettingsPayload } from "@/lib/types";+import { Sample, StatePicker, type ComponentExample } from "./example";++const providers: SettingsPayload["providers"] = [+ { name: "openai", label: "OpenAI", configured: true, auth_type: "api_key", model_catalog: "builtin", model_api_configurable: true,+ request_apis: ["responses", "chat_completions"], provider_api_configurable: true },+ { name: "anthropic", label: "Anthropic", configured: true, auth_type: "api_key", model_catalog: "builtin", request_apis: ["anthropic_messages"] },+ { name: "openai_codex", label: "OpenAI Codex", configured: true, auth_type: "oauth", model_catalog: "builtin" },+ { name: "ollama", label: "Ollama", configured: true, auth_type: "api_key", model_catalog: "local" },+];++export const settings: SettingsPayload = {+ agent: { model: "gpt-5.4", provider: "openai", resolved_provider: "openai", has_api_key: true, model_preset: null,+ max_tokens: 8192, context_window_tokens: 200_000, temperature: 0.1, reasoning_effort: null, timezone: "UTC", tool_hint_max_length: 40 },+ model_presets: [], model_call_order: [], model_call_order_editable: true,+ providers,+ web_search: { provider: "duckduckgo", max_results: 5, timeout: 30, providers: [+ { name: "duckduckgo", label: "DuckDuckGo", credential: "none" },+ { name: "brave", label: "Brave Search", credential: "api_key" },+ { name: "searxng", label: "SearXNG", credential: "base_url" },+ ] },+ web: { enable: true, search: { max_results: 5, timeout: 30 }, fetch: { use_jina_reader: true } },+ image_generation: { enabled: true, provider: "openai", provider_configured: true, model: "gpt-image-1",+ default_aspect_ratio: "1:1", default_image_size: "1024x1024", max_images_per_turn: 4, save_dir: "workspace/images",+ providers: [{ name: "openai", label: "OpenAI", configured: true, uses_images_api: true,+ default_api_base: "https://api.openai.com/v1", models: ["gpt-image-1", "gpt-image-1-mini"] }] },+ transcription: { enabled: true, provider: "groq", provider_configured: true, model: "whisper-large-v3", language: null,+ max_duration_sec: 120, max_upload_mb: 25, providers: [{ name: "groq", label: "Groq", configured: true }] },+ runtime: { config_path: "config.json", workspace_path: "workspace", gateway_host: "127.0.0.1", gateway_port: 8765,+ heartbeat: { enabled: true, interval_s: 1800 }, dream: { schedule: "0 3 * * *" }, unified_session: false },+ advanced: { restrict_to_workspace: true, ssrf_whitelist_count: 0, webui_allow_local_service_access: true,+ webui_default_access_mode: "default", private_service_protection_enabled: true, mcp_server_count: 0,+ exec_enabled: true, exec_path_prepend_set: false, exec_path_append_set: false },+ requires_restart: false,+};++function usePreviewForm<T>(initial: T) {+ const [form, setForm] = useState(initial);+ const [saved, setSaved] = useState(initial);+ const dirty = JSON.stringify(form) !== JSON.stringify(saved);+ return { form, setForm, dirty, save: () => setSaved(form) };+}++function FormStatus({ dirty }: { dirty: boolean }) {+ return <p role="status" className="mt-4 text-xs text-muted-foreground">{dirty ? "正在保存预览值…" : "预览值已保存"}</p>;+}++function ModelPickerPreview() {+ const [provider, setProvider] = useState("openai");+ const [model, setModel] = useState("gpt-5.4");+ const [effort, setEffort] = useState("medium");+ const [action, setAction] = useState("");+ const models = provider === "anthropic" ? ["claude-sonnet-4", "claude-opus-4"] : ["gpt-5.4", "gpt-5-mini", "gpt-4.1"];+ return <div className="settings-grid space-y-4">+ <SettingsGroup>+ <SettingsRow title="服务商"><ProviderPicker providers={providers.slice(0, 2)} value={provider} emptyLabel="选择服务商"+ onChange={(next) => { setProvider(next); setModel(next === "anthropic" ? "claude-sonnet-4" : "gpt-5.4"); }}+ onAddProvider={() => setAction("添加服务商")}+ onConfigureProvider={(next) => setAction(`配置 ${next}`)} /></SettingsRow>+ <SettingsRow title="模型"><ModelIdPicker token="" settings={settings} provider={provider} models={models}+ value={model} showProviderLogos={false} onChange={setModel} /></SettingsRow>+ <SettingsRow title="推理强度"><ReasoningEffortPicker token="" provider={undefined} model={model}+ savedValues={["low", "medium", "high"]} value={effort} onChange={setEffort} /></SettingsRow>+ </SettingsGroup>+ <p role="status" className="text-xs text-muted-foreground">{provider} / {model} / {effort || "default"}{action ? ` · ${action}` : ""}</p>+ </div>;+}++function ProviderIconsPreview() {+ const [size, setSize] = useState<"regular" | "compact" | "fill">("regular");+ return <><StatePicker label="图标尺寸" value={size} options={["regular", "compact", "fill"]} onChange={setSize} />+ <div className="flex flex-wrap gap-8">{providers.map((provider) => <Sample key={provider.name} label={provider.label}>+ <div className="flex items-center gap-3"><span className={size === "fill" ? "block h-12 w-12" : ""}>+ <ProviderIcon provider={provider.name} compact={size === "compact"} fill={size === "fill"} showBrandLogos={false} />+ </span><ProviderPickerIcon provider={provider.name} showBrandLogos={false} />+ <ProviderPickerIcon provider={provider.name} showBrandLogos={false} unconfigured /></div>+ </Sample>)}</div></>;+}++function TimezonePreview() {+ const [value, setValue] = useState("Asia/Shanghai");+ return <div className="max-w-sm space-y-4"><TimezonePicker value={value} onChange={setValue} aria-label="选择时区" />+ <p role="status" className="text-sm text-muted-foreground">{new Intl.DateTimeFormat("zh-CN", {+ timeZone: value, dateStyle: "medium", timeStyle: "short",+ }).format(Date.UTC(2026, 0, 1, 12))} · {value}</p></div>;+}++function TextEditorPreview() {+ const [value, setValue] = useState("Keep replies concise. Explain the reason for a change.");+ const [mode, setMode] = useState<"editable" | "disabled">("editable");+ return <><StatePicker label="编辑状态" value={mode} options={["editable", "disabled"]} onChange={setMode} />+ <SettingsGroup><SettingsRow title={<SettingsHint description="打开编辑器后可以修改、保存或取消。清空内容可查看错误状态。">示例说明</SettingsHint>}>+ <SettingsTextEditor title="编辑示例说明" description="保存后,下方显示修改的内容。" value={value} disabled={mode === "disabled"}+ onSave={(next) => { if (!next.trim()) throw new Error("请输入内容。"); setValue(next); }} />+ </SettingsRow></SettingsGroup>+ <pre role="status" className="mt-4 whitespace-pre-wrap rounded-control bg-muted p-4 text-sm">{value}</pre></>;+}++function RemovePresetPreview() {+ const initial = [{ id: 1, name: "默认模型", primary: true }, { id: 2, name: "代码助手", primary: false }];+ const [items, setItems] = useState(initial);+ return <div className="settings-grid"><SettingsGroup>+ {items.map((item) => <SettingsRow key={item.id} title={item.name}>+ <RemoveActionButton disabled={item.primary} aria-label={`删除 ${item.name}`}+ aria-describedby={item.primary ? "gallery-primary-model-hint" : undefined}+ onClick={() => setItems((current) => current.filter((entry) => entry.id !== item.id))}>删除</RemoveActionButton>+ </SettingsRow>)}+ </SettingsGroup><p id="gallery-primary-model-hint" className="mt-4 text-xs text-muted-foreground">默认模型使用中的预设不能删除。</p>+ <p role="status" className="mt-2 text-xs text-muted-foreground">{items.length} 个预览预设</p>+ <Button className="mt-3" variant="outline" size="sm" onClick={() => setItems(initial)}>重置预览</Button></div>;+}++function LoadingPreview() {+ const [layout, setLayout] = useState<"apps" | "channels" | "skills">("apps");+ return <><StatePicker label="目录布局" value={layout} options={["apps", "channels", "skills"]} onChange={setLayout} />+ <Sample label="CatalogSkeleton"><CatalogSkeleton label="正在加载预览目录" layout={layout} /></Sample>+ <div className="mt-6"><Sample label="SkeletonStatus"><SkeletonStatus label="正在加载设置" className="space-y-3">+ <div className="h-4 w-1/3 rounded bg-muted" /><div className="h-9 rounded-control bg-muted" />+ </SkeletonStatus></Sample></div></>;+}++function SidebarPreview() {+ const [section, setSection] = useState<SettingsSectionKey>("models");+ const [pending, setPending] = useState(true);+ const [action, setAction] = useState("");+ return <div className="flex min-h-96 flex-col gap-6 lg:flex-row">+ <SettingsSidebar activeSection={section} onSelectSection={setSection} restartPending={pending}+ onBackToChat={() => setAction("返回聊天")}+ onLogout={() => setAction("退出登录")}+ onRestart={() => { setPending(false); setAction("已处理预览重启操作"); }} />+ <div className="space-y-3 p-4"><p role="status" className="text-sm">选中:{section}</p>+ <p className="text-xs text-muted-foreground">{action || "选择设置分类,或缩小浏览器查看移动端导航。"}</p>+ <Button variant="outline" size="sm" onClick={() => setPending((value) => !value)}>切换待重启状态</Button></div>+ </div>;+}++function ProviderSearchPreview() {+ const [query, setQuery] = useState("");+ const [selected, setSelected] = useState("");+ return <><div className="flex h-[400px] flex-col overflow-hidden rounded-panel border pt-4">+ <ProviderSearchList providers={providers} showBrandLogos={false} query={query} onQueryChange={setQuery}+ onSelect={setSelected} onCustom={() => setSelected("custom")} onClose={() => { setQuery(""); setSelected("已关闭搜索"); }} />+ </div><p role="status" className="mt-4 text-sm text-muted-foreground">{selected ? `选择:${selected}` : "搜索服务商,或用方向键选择。"}</p></>;+}++function RequestParametersPreview() {+ const [form, setForm] = useState<RequestParameterDraft>({ extraHeaders: '{"X-Project":"gallery"}', extraQuery: "{}", extraBody: '{"service_tier":"auto"}' });+ return <div className="space-y-4"><ProviderParameterFields fields={["extra_headers", "extra_query", "extra_body"]} form={form}+ onChange={(next) => setForm((current) => ({ ...current, ...next }))} />+ <pre role="status" className="overflow-auto rounded-control bg-muted p-4 text-xs">{JSON.stringify(form, null, 2)}</pre></div>;+}++function RequestAPIPreview() {+ const [providerAPI, setProviderAPI] = useState<ModelAPIConfig>({ supported_apis: ["responses", "chat_completions"], preferred_api: "responses" });+ const [modelAPI, setModelAPI] = useState<ModelAPIConfig | null>(null);+ return <div className="grid gap-8 md:grid-cols-2">+ <Sample label="服务商协议"><ProviderAPIControl value={providerAPI} onChange={setProviderAPI} /></Sample>+ <Sample label="模型覆盖"><SettingsGroup><ModelAPIControl provider={providers[0]} automaticAPI="responses" value={modelAPI} onChange={setModelAPI} /></SettingsGroup></Sample>+ <pre role="status" className="overflow-auto rounded-control bg-muted p-4 text-xs md:col-span-2">{JSON.stringify({ providerAPI, modelAPI }, null, 2)}</pre>+ </div>;+}++type Usage = NonNullable<SettingsPayload["usage"]>;+const usage: Usage = (() => {+ const now = new Date();+ const days: Usage["days"] = Array.from({ length: 30 }, (_, index) => {+ const date = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() - 29 + index));+ const scale = index % 7 === 0 ? 0 : index % 5 + 1;+ return { date: date.toISOString().slice(0, 10), input_tokens: scale * 4000, output_tokens: scale * 1000,+ cache_read_tokens: scale * 2000, cache_write_tokens: 0, cache_read_observed_input_tokens: scale * 3000,+ cache_write_observed_input_tokens: 0, total_tokens: scale * 5000, requests: scale * 2 };+ });+ const total = days.reduce((sum, day) => sum + day.total_tokens, 0);+ return { days, total_tokens: total, total_tokens_30d: total, total_tokens_365d: total,+ peak_day_tokens: Math.max(...days.map((day) => day.total_tokens)), current_streak_days: 3, longest_streak_days: 6,+ active_days_30d: days.filter((day) => day.total_tokens > 0).length, requests_30d: days.reduce((sum, day) => sum + day.requests, 0),+ model_days_30d: days.flatMap((day) => [+ { date: day.date, provider: "openai", model: "gpt-5.4", total_tokens: day.total_tokens * 0.6 },+ { date: day.date, provider: "anthropic", model: "claude-sonnet-4", total_tokens: day.total_tokens * 0.4 },+ ]) };+})();++function UsagePreview() {+ const [mode, setMode] = useState<"active" | "empty" | "unavailable">("active");+ return <><StatePicker label="用量状态" value={mode} options={["active", "empty", "unavailable"]} onChange={setMode} />+ <TokenUsageCard usage={mode === "unavailable" ? undefined : mode === "empty" ? { ...usage, days: [], model_days_30d: [] } : usage} timeZone="UTC" /></>;+}++function OverviewPreview() {+ const [section, setSection] = useState<SettingsSectionKey>("overview");+ return <><OverviewSettings settings={{ ...settings, usage }} showBrandLogos={false} onSelectSection={setSection} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">选择的分类:{section}</p></>;+}++function WebPreview() {+ const [savedSettings, setSavedSettings] = useState(settings);+ const [form, setForm] = useState(webSearchFormFromPayload(settings));+ const [keyVisible, setKeyVisible] = useState(false);+ const [keyEditing, setKeyEditing] = useState(false);+ const { dirty } = webSearchDraftState(savedSettings, form);+ return <><WebSettings settings={savedSettings} form={form} saving={false} keyVisible={keyVisible} keyEditing={keyEditing}+ onChangeForm={setForm} onChangeProvider={(provider) => setForm((current) => ({ ...current, provider, apiKey: "", baseUrl: "" }))}+ onToggleKey={() => setKeyVisible((value) => !value)} onToggleKeyEditing={() => setKeyEditing((value) => !value)}+ onReset={() => setForm(webSearchFormFromPayload(savedSettings))}+ onSave={() => {+ setSavedSettings((current) => ({ ...current,+ web_search: { ...current.web_search, provider: form.provider,+ api_key_hint: form.apiKey ? "••••••••" : form.provider === current.web_search.provider ? current.web_search.api_key_hint : undefined,+ base_url: form.baseUrl, max_results: form.maxResults ?? current.web_search.max_results, timeout: form.timeout ?? current.web_search.timeout },+ web: { ...current.web, fetch: { use_jina_reader: form.useJinaReader ?? current.web.fetch.use_jina_reader } },+ })); setForm((current) => ({ ...current, apiKey: "" })); setKeyEditing(false);+ }} showBrandLogos={false} requiresRestartPending={false} olostepInstalling={false} capabilityError={null} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">{dirty ? "预览草稿尚未保存" : "预览值已保存"}</p></>;+}++function ImagePreview() {+ const { form, setForm, dirty, save } = usePreviewForm(imageGenerationFormFromPayload(settings));+ const [notice, setNotice] = useState("");+ return <><ImageGenerationSettings token="" settings={settings} form={form} dirty={dirty} saving={false}+ onChangeForm={setForm} onSave={save} showBrandLogos={false} requiresRestartPending={false}+ onSaveRequestSettings={async (next) => setForm((current) => ({ ...current, ...next }))}+ onOpenProviders={() => setNotice("选择了服务商配置操作")} />+ <FormStatus dirty={dirty} />{notice ? <p className="mt-2 text-xs text-muted-foreground">{notice}</p> : null}</>;+}++function VoicePreview() {+ const { form, setForm, dirty, save } = usePreviewForm(transcriptionFormFromPayload(settings));+ const [notice, setNotice] = useState("");+ return <><TranscriptionSettings settings={settings} form={form} dirty={dirty} saving={false} onChangeForm={setForm}+ onSave={save} showBrandLogos={false} requiresRestartPending={false} onOpenProviders={() => setNotice("选择了服务商配置操作")} />+ <FormStatus dirty={dirty} />{notice ? <p className="mt-2 text-xs text-muted-foreground">{notice}</p> : null}</>;+}++function SafetyPreview() {+ const { form, setForm, dirty, save } = usePreviewForm(networkSafetyFormFromPayload(settings));+ return <><AdvancedSettings form={form} dirty={dirty} saving={false} requiresRestartPending={false}+ isNativeHostSurface={false} onChangeForm={setForm} onSave={save} /><FormStatus dirty={dirty} /></>;+}++const channel: NanobotFeatureInfo = {+ name: "gallery_channel", display_name: "Example channel", type: "channel", enabled: false, installed: true,+ configured: true, ready: true, status: "not_enabled", install_supported: true, requires_restart: false, runtime_status: "stopped",+ setup: { fields: [], official_url: "https://nanobot.wiki/docs/latest/getting-started/chat-apps" },+};++function ChannelCatalogPreview() {+ const [mode, setMode] = useState<"stopped" | "running" | "starting" | "failed" | "uninstalled">("stopped");+ const [selected, setSelected] = useState(false);+ const feature = { ...channel, enabled: mode === "running" || mode === "starting", installed: mode !== "uninstalled",+ runtime_status: mode === "uninstalled" ? "stopped" : mode, runtime_error: mode === "failed" ? "Example connection failed." : undefined };+ return <><StatePicker label="频道状态" value={mode} options={["stopped", "running", "starting", "failed", "uninstalled"]} onChange={setMode} />+ <div className="settings-grid"><SettingsGroup><ChannelCatalogRow feature={feature} showBrandLogos={false} actionKey={null}+ onSelect={() => setSelected(true)} onAction={(action, _name, options) => setMode(options?.installOnly ? "stopped" : action === "enable" ? "running" : "stopped")} /></SettingsGroup></div>+ <div className="mt-4 flex items-center gap-3"><ChannelLogo feature={feature} showBrandLogos={false} />+ <ChannelStatusBadge status={feature.runtime_status}>{feature.runtime_status}</ChannelStatusBadge>+ <ChannelHelpMenu feature={feature} /></div>+ <ChannelRuntimeError message={feature.runtime_error} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">{selected ? "选择了频道设置" : "点击开关或安装按钮,查看状态变化。"}</p></>;+}++const channelFields: ChannelConfigField[] = [+ { key: "bot_token", label: "Bot token", secret: true, section: "credentials", placeholder: "Example token" },+ { key: "server_url", label: "Server URL", inputType: "url", section: "connection", optional: true },+ { key: "mode", label: "Reply mode", section: "behavior", options: [{ value: "mention", label: "Mentions" }, { value: "all", label: "All messages" }] },+ { key: "allow_from", label: "Allow from", section: "access", kind: "json", optional: true, placeholder: '["user-id"]' },+];+const channelPresets: ChannelProviderPreset[] = [+ { id: "local", label: "Local server", values: { server_url: "http://127.0.0.1:8080", mode: "mention" } },+ { id: "hosted", label: "Hosted server", values: { server_url: "https://example.com", mode: "all" } },+];++function CredentialsPreview() {+ const [values, setValues] = useState<Record<string, string>>({ bot_token: "", server_url: "", mode: "mention", allow_from: "[]" });+ const [visibleSecrets, setVisibleSecrets] = useState<Record<string, boolean>>({});+ const [errors, setErrors] = useState<Record<string, string>>({});+ const [notice, setNotice] = useState<string | null>(null);+ return <div className="space-y-5">+ <ChannelProviderPresets presets={channelPresets} onApply={(preset) => { setValues((current) => ({ ...current, ...preset.values })); setNotice(`已应用 ${preset.label}`); }} />+ <ChannelFieldGroups fields={channelFields} requirements={[{ alternatives: [["bot_token"]] }]} values={values} visibleSecrets={visibleSecrets}+ errors={errors} onChange={(key, value) => { setValues((current) => ({ ...current, [key]: value })); setErrors({}); }}+ onToggleSecret={(key) => setVisibleSecrets((current) => ({ ...current, [key]: !current[key] }))} />+ <div className="flex flex-wrap items-center gap-3"><Button variant="outline" onClick={() => {+ const next = channelRequirementErrors(channelFields, [{ alternatives: [["bot_token"]] }], values, new Set(), new Set(), "请输入 Bot token。");+ setErrors(next); setNotice(Object.keys(next).length ? "请补全凭据。" : "预览凭据已保存。");+ }}>检查并保存</Button><ChannelSetupActions feature={channel} setup={{ actions: [{ id: "copy", label: "Example command", copyText: "nanobot gateway" }] }} onNotice={setNotice} /></div>+ <p role="status" className="text-xs text-muted-foreground">{notice || "填写凭据、切换密文显示,或应用连接预设。"}</p>+ </div>;+}++function ChannelValidationPreview() {+ const [mode, setMode] = useState<"checking" | "connected" | "invalid">("connected");+ const validation = useMemo<ChannelValidationPayload | null>(() => mode === "checking" ? null : {+ name: channel.name, status: mode, identity: { name: "Example bot", workspace: "Gallery workspace" },+ checks: [{ id: "credentials", label: "Credentials", status: "pass" },+ { id: "connection", label: "Connection", status: mode === "invalid" ? "fail" : "pass", message: mode === "invalid" ? "The example token has expired." : undefined }],+ missing_fields: [], can_enable: mode === "connected", requires_restart: false,+ }, [mode]);+ return <><StatePicker label="检查结果" value={mode} options={["checking", "connected", "invalid"]} onChange={setMode} />+ <ChannelValidationProgress validation={validation} validating={mode === "checking"} feature={channel} /></>;+}++function RunAtPreview() {+ const [value, setValue] = useState("2026-10-15T09:30");+ return <div className="max-w-md space-y-4"><AutomationRunAtPicker value={value} onChange={setValue} />+ <p role="status" className="text-sm text-muted-foreground">{value}</p></div>;+}++function AutomationCalendarPreview() {+ const [month, setMonth] = useState(() => { const now = new Date(); return new Date(now.getFullYear(), now.getMonth(), 1); });+ const [mode, setMode] = useState<"scheduled" | "history" | "empty">("scheduled");+ const [selected, setSelected] = useState("");+ const jobs: SessionAutomationJob[] = mode === "empty" ? [] : [{ id: "gallery-reminder", name: "Weekly report", enabled: mode === "scheduled",+ schedule: { kind: "cron", expr: "30 9 * * 1", tz: "UTC" }, payload: { message: "Summarize this week's changes." },+ state: { next_run_at_ms: mode === "scheduled" ? new Date(month.getFullYear(), month.getMonth(), 15, 9, 30).getTime() : null,+ run_history: [{ run_at_ms: new Date(month.getFullYear(), month.getMonth(), 8, 9, 30).getTime(), status: "ok", duration_ms: 3200, webui_session_key: null },+ { run_at_ms: new Date(month.getFullYear(), month.getMonth(), 1, 9, 30).getTime(), status: "error", duration_ms: 1200, error: "Example provider was unavailable.", webui_session_key: null }] } }];+ return <><StatePicker label="日程状态" value={mode} options={["scheduled", "history", "empty"]} onChange={setMode} />+ <div className="mb-4 flex flex-wrap items-center gap-3"><Button size="sm" variant="outline" onClick={() => setMonth(new Date(month.getFullYear(), month.getMonth() - 1, 1))}>上个月</Button>+ <span className="text-sm">{new Intl.DateTimeFormat("zh-CN", { year: "numeric", month: "long" }).format(month)}</span>+ <Button size="sm" variant="outline" onClick={() => setMonth(new Date(month.getFullYear(), month.getMonth() + 1, 1))}>下个月</Button></div>+ <AutomationCalendar jobs={jobs} month={month} locale="zh-CN" onInspect={(job) => setSelected(job.name)}+ renderRunDialog={(props) => <AutomationRunDialogView {...props} result={{ status: "loaded", response: "**运行结果**\n\n示例任务已处理当前项目更新。" }} onRetry={() => {}} />}+ copy={{+ planned: "已计划", recorded: "运行记录", running: "正在运行", failed: "失败", completed: "完成", skipped: "已跳过", system: "系统任务",+ close: "关闭", noEntries: "本月没有日程", more: (count) => `另外 ${count} 条`,+ }} /><p role="status" className="mt-4 text-xs text-muted-foreground">{selected ? `选择了任务:${selected}` : "点击运行记录查看结果,或选择计划中的任务。"}</p></>;+}++const components = "webui/src/components/settings/";+export const settingsExamples: ComponentExample[] = [+ { title: "Model pickers · 模型选择", files: ["shared/ModelControls", "models/ReasoningEffortPicker"], Preview: ModelPickerPreview,+ description: "选择服务商、搜索或输入模型 ID,并调整推理强度。",+ options: "ProviderPicker 的值与操作由调用方提供。ModelIdPicker 的 models 参数可提供固定目录;ReasoningEffortPicker 的 savedValues 提供已有选项。",+ code: '<ProviderPicker providers={providers} value={provider} onChange={setProvider} emptyLabel="选择服务商" />\n<ModelIdPicker token="" settings={settings} provider={provider} models={modelIds} value={model} showProviderLogos={false} onChange={setModel} />' },+ { title: "Provider icons · 服务商图标", files: ["shared/ProviderIcon"], Preview: ProviderIconsPreview,+ description: "比较普通、紧凑与填充尺寸,以及选择器的未配置状态。", options: "provider 选择已有图标;compact 与 fill 控制尺寸。showBrandLogos=false 使用内置图标。",+ code: '<ProviderIcon provider="openai" showBrandLogos={false} compact />\n<ProviderPickerIcon provider="openai" showBrandLogos={false} unconfigured />' },+ { title: "TimezonePicker · 时区选择", files: ["shared/TimezonePicker"], Preview: TimezonePreview,+ description: "按时区名、中文名称或 UTC 偏移搜索,选择后查看同一时刻的当地时间。", options: "value 是 IANA 时区;onChange 更新调用方的值。搜索与键盘导航由组件提供。",+ code: '<TimezonePicker value={timezone} onChange={setTimezone} aria-label="选择时区" />' },+ { title: "Text editor and hint · 文本编辑", files: ["shared/SettingsTextEditor", "shared/SettingsHint"], Preview: TextEditorPreview,+ description: "打开编辑弹窗,修改、保存或取消。清空内容后保存可查看错误反馈。", options: "SettingsTextEditor 在 onSave 成功后关闭,失败时显示错误;SettingsHint 可通过悬停、焦点或点击打开。",+ code: '<SettingsHint description="补充说明">标题</SettingsHint>\n<SettingsTextEditor title="编辑说明" value={value} onSave={setValue} />' },+ { title: "RemoveActionButton · 删除预设", files: ["shared/RemoveActionButton"], Preview: RemovePresetPreview,+ description: "删除未使用的模型预设,查看默认模型使用中预设的禁用状态。", options: "这是 ModelsSettings 使用的删除按钮;disabled 与删除动作由调用方提供。提供商管理使用 ProvidersSettings 弹窗。",+ code: '<RemoveActionButton disabled={referenced} onClick={deletePreset}>删除</RemoveActionButton>' },+ { title: "Loading layouts · 加载占位", files: ["shared/CatalogSkeleton", "shared/SkeletonStatus"], Preview: LoadingPreview,+ description: "切换应用、频道与技能目录的加载布局,并查看通用状态容器。", options: "CatalogSkeleton 的 layout 选择布局。SkeletonStatus 用 label 提供读屏状态,将装饰内容标为 aria-hidden。",+ code: '<CatalogSkeleton label="正在加载目录" layout="channels" />\n<SkeletonStatus label="正在加载设置" className="space-y-3">{skeletons}</SkeletonStatus>' },+ { title: "SettingsSidebar · 设置导航", files: ["SettingsSidebar"], Preview: SidebarPreview,+ description: "选择分类、处理待重启状态,并缩小浏览器查看移动端菜单。", options: "activeSection 与 onSelectSection 控制选择;返回、退出与重启动作为调用方回调。",+ code: '<SettingsSidebar activeSection={section} onSelectSection={setSection} onBackToChat={back} onRestart={restart} restartPending />' },+ { title: "ProviderSearchList · 服务商搜索", files: ["models/ProviderSearchList"], Preview: ProviderSearchPreview,+ description: "搜索按 OAuth、API Key 与本地分组的服务商,选择条目或自定义服务商。", options: "providers 是已有目录。query 为受控搜索值;onSelect 与 onCustom 将选择交给父组件。",+ code: '<ProviderSearchList providers={providers} query={query} onQueryChange={setQuery} showBrandLogos={false} onSelect={select} onCustom={custom} onClose={close} />' },+ { title: "ProviderParameterFields · 请求参数", files: ["models/ProviderParameterFields"], Preview: RequestParametersPreview,+ description: "编辑请求头、查询参数和请求体;输入无效 JSON 可查看真实校验反馈。", options: "fields 选择显示项,form 保存 JSON 文本。请求头与查询参数只接受字符串值;请求体接受任意 JSON 对象值。",+ code: '<ProviderParameterFields fields={["extra_headers", "extra_query", "extra_body"]} form={draft} onChange={updateDraft} />' },+ { title: "Request API controls · 请求协议", files: ["models/ProviderAPIControl", "models/ModelAPIControl"], Preview: RequestAPIPreview,+ description: "选择服务商支持的协议、默认协议,以及模型覆盖和回退选项。", options: "ProviderAPIControl 至少保留一个协议。ModelAPIControl 允许 null 表示自动选择,并按服务商能力显示可用协议。",+ code: '<ProviderAPIControl value={api} onChange={setAPI} />\n<ModelAPIControl provider={provider} automaticAPI="responses" value={modelAPI} onChange={setModelAPI} />' },+ { title: "Token usage · 用量统计", files: ["TokenUsageCard", "TokenUsageDetails", "TokenUsageModelTrend"], Preview: UsagePreview,+ description: "切换有数据、空记录和不可用状态。悬停柱图查看每日用量,打开详情查看模型趋势。", options: "usage 是调用方提供的统计记录;timeZone 定义日期范围。详情弹窗与图表只展示传入数据。",+ code: '<TokenUsageCard usage={usage} timeZone="UTC" />' },+ { title: "OverviewSettings · 设置概览", files: ["overview/OverviewSettings"], Preview: OverviewPreview,+ description: "查看当前模型、能力状态和用量统计,点击功能行体验分类选择。", options: "settings 提供概览数据;onSelectSection 接收选择的设置分类。",+ code: '<OverviewSettings settings={settings} showBrandLogos={false} onSelectSection={setSection} />' },+ { title: "WebSettings · 搜索设置", files: ["capabilities/WebSettings"], Preview: WebPreview,+ description: "切换免凭据、API Key 与服务器地址三种服务商,调整搜索选项并体验自动保存。", options: "settings 保存当前配置,form 保存编辑值。保存、凭据显示与服务商切换由父组件提供。",+ code: '<WebSettings settings={settings} form={form} onChangeForm={setForm} onSave={save} {...actions} />' },+ { title: "ImageGenerationSettings · 图像设置", files: ["capabilities/ImageGenerationSettings"], Preview: ImagePreview,+ description: "开关图像生成,选择固定模型目录、宽高比与图片尺寸,展开高级选项调整数量。", options: "form 为受控配置,dirty 标记修改。组件复用服务商凭据,保存动作由父组件实现。",+ code: '<ImageGenerationSettings token="" settings={settings} form={form} dirty={dirty} onChangeForm={setForm} onSave={save} {...actions} />' },+ { title: "TranscriptionSettings · 语音设置", files: ["capabilities/TranscriptionSettings"], Preview: VoicePreview,+ description: "切换转写开关,编辑模型、语言与时长和上传大小限制,体验自动保存。", options: "settings 提供服务商信息;form 与保存回调由父组件管理。",+ code: '<TranscriptionSettings settings={settings} form={form} dirty={dirty} onChangeForm={setForm} onSave={save} {...actions} />' },+ { title: "AdvancedSettings · 访问设置", files: ["capabilities/SecuritySettings"], Preview: SafetyPreview,+ description: "切换本地服务访问与默认权限,查看设置行、提示和自动保存反馈。", options: "form 是显示值;onSave 处理保存请求。运行时的权限执行仍由 gateway 负责。",+ code: '<AdvancedSettings form={form} dirty={dirty} saving={false} requiresRestartPending={false} isNativeHostSurface={false} onChangeForm={setForm} onSave={save} />' },+ { title: "Channel catalog and identity · 频道条目", files: ["channels/ChannelCatalogRow", "channels/ChannelIdentity", "channels/ChannelHelpMenu"], Preview: ChannelCatalogPreview,+ description: "切换运行、启动、失败和未安装状态;操作开关、安装入口与帮助菜单。", options: "feature 提供安装和运行状态。onAction 与 onSelect 交给父组件处理;标识、错误和帮助使用同一频道数据。",+ code: '<ChannelCatalogRow feature={feature} showBrandLogos={false} actionKey={null} onSelect={select} onAction={act} />' },+ { title: "Channel credentials · 频道表单", files: ["channels/CredentialForm", "channels/ChannelCredentialFields", "channels/ChannelSetupParts"], Preview: CredentialsPreview,+ description: "输入凭据,显示或隐藏密文,应用连接预设,检查必填字段并复制辅助命令。", options: "fields 定义分组与控件,values 和 visibleSecrets 为受控值。requirements 定义凭据组合;预设与保存回调只更新此示例。",+ code: '<ChannelFieldGroups fields={fields} requirements={requirements} values={values} visibleSecrets={visible} onChange={change} onToggleSecret={toggle} />' },+ { title: "ChannelValidationProgress · 连接检查", files: ["channels/ChannelValidationProgress"], Preview: ChannelValidationPreview,+ description: "切换检查中、成功和失败,观察逐项揭示的检查结果与身份摘要。", options: "validation 提供检查记录,validating 控制加载状态;组件只负责展示。",+ code: '<ChannelValidationProgress feature={feature} validation={validation} validating={checking} />' },+ { title: "AutomationRunAtPicker · 定时选择", files: ["system/AutomationRunAtPicker"], Preview: RunAtPreview,+ description: "输入日期时间,或打开日历并用鼠标、方向键和翻页键选择日期。", options: "value 使用 YYYY-MM-DDTHH:mm 本地时间;onChange 返回编辑值。错误输入显示在现有表单控件上。",+ code: '<AutomationRunAtPicker value={runAt} onChange={setRunAt} />' },+ { title: "Automation calendar · 任务日历", files: ["system/AutomationCalendar"], Preview: AutomationCalendarPreview,+ description: "翻月、切换计划与历史记录,点击成功或失败记录打开结果弹窗。窄容器自动显示日程列表。", options: "jobs 与 month 决定日历内容。onInspect 处理计划中的任务;renderRunDialog 由调用方提供结果展示,日历不读取服务。",+ code: '<AutomationCalendar jobs={jobs} month={month} locale="zh-CN" copy={copy} onInspect={inspect} renderRunDialog={renderRunDialog} />' },+].map((example) => ({ ...example, files: example.files.map((file) => `${components}${file}.tsx`) }));diff --git a/webui/src/dev/gallery/shared-views.tsx b/webui/src/dev/gallery/shared-views.tsxnew file mode 100644index 000000000..82880fd8c--- /dev/null+++ b/webui/src/dev/gallery/shared-views.tsx@@ -0,0 +1,144 @@+import { useState } from "react";+import { Check, CircleAlert } from "lucide-react";++import { AttachmentTile } from "@/components/AttachmentTile";+import { CodeBlock } from "@/components/CodeBlock";+import { ImageGallery } from "@/components/ImageGallery";+import { MarkdownText } from "@/components/MarkdownText";+import { MessageBubble } from "@/components/MessageBubble";+import { FileReferenceChip } from "@/components/FileReferenceChip";+import { ActivityStep } from "@/components/thread/activity/ActivityStep";+import { ReasoningRow } from "@/components/thread/activity/ReasoningRow";+import { ThinkingReasoningShell } from "@/components/thread/activity/ThinkingReasoningShell";+import { FileEditGroup, type FileEditSummary } from "@/components/thread/activity/FileEditRow";+import { GenericToolRun } from "@/components/thread/activity/GenericToolRun";+import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";+import { SettingsFeature } from "@/components/settings/shared/SettingsFeature";+import { Input } from "@/components/ui/input";+import { ToggleButton } from "@/components/ui/toggle-button";+import type { UIMessage } from "@/lib/types";+import { Sample, StatePicker, type ComponentExample } from "./example";++const markdown = `## A small result\n\nA reply can contain **emphasis**, a list, and inline math $a^2 + b^2 = c^2$.\n\n- Read the source\n- Reuse the existing component\n\n| Item | State |\n| --- | --- |\n| UI | Ready |\n\n\`\`\`python\nprint("Hello, Nanobot")\n\`\`\``;++function MarkdownPreview() {+ const [state, setState] = useState<"complete" | "streaming">("complete");+ return <><StatePicker label="Markdown state" value={state} options={["complete", "streaming"]} onChange={setState} />+ <MarkdownText streaming={state === "streaming"}>{state === "streaming" ? markdown.slice(0, 100) : markdown}</MarkdownText></>;+}++function CodePreview() {+ const [mode, setMode] = useState<"code" | "terminal" | "viewport">("code");+ return <><StatePicker label="Code format" value={mode} options={["code", "terminal", "viewport"]} onChange={setMode} />+ <CodeBlock language={mode === "terminal" ? "ansi" : "tsx"} showLineNumbers={mode !== "terminal"}+ viewportHighlight={mode === "viewport"} wrapLongLines={mode !== "viewport"}+ code={mode === "terminal" ? "\u001b[32mPASS\u001b[0m Component preview ready\n\u001b[33mNOTE\u001b[0m No gateway connection" : '<Button variant="outline" onClick={save}>\n Save changes\n</Button>'} /></>;+}++function MessagePreview() {+ const [state, setState] = useState<"answer" | "thinking" | "streaming" | "sending" | "failed">("answer");+ const user: UIMessage = {+ id: "gallery-user", role: "user", content: "Show me how this component works.", createdAt: Date.UTC(2026, 0, 1, 12),+ deliveryStatus: state === "sending" ? "sending" : state === "failed" ? "failed" : "accepted",+ deliveryErrorKind: state === "failed" ? "turn_rejected" : undefined,+ };+ const assistant: UIMessage = {+ id: "gallery-assistant", role: "assistant", createdAt: user.createdAt + 1000,+ content: state === "thinking" ? "" : "Here is a **reusable message** with the same typography and actions as the chat.",+ isStreaming: state === "thinking" || state === "streaming",+ };+ return <><StatePicker label="Message state" value={state} options={["answer", "thinking", "streaming", "sending", "failed"]} onChange={setState} />+ <div className="space-y-6"><MessageBubble message={user} />+ {state !== "sending" && state !== "failed" ? <MessageBubble message={assistant} /> : null}</div></>;+}++function ActivityPreview() {+ const [state, setState] = useState<"running" | "done" | "error">("running");+ const [expanded, setExpanded] = useState(true);+ return <><StatePicker label="Activity state" value={state} options={["running", "done", "error"]} onChange={setState} />+ <ThinkingReasoningShell active={state === "running"} expanded={expanded} label={state === "running" ? "Working" : "Activity details"}+ collapseLabel="Collapse" onToggle={() => setExpanded((value) => !value)}>+ <ReasoningRow text="Checking the component's inputs and shared styles." streaming={state === "running"} />+ <ActivityStep icon={state === "error" ? CircleAlert : Check} active={state === "running"}+ tone={state === "error" ? "error" : "success"} label={state === "error" ? "Could not read file" : "Read source"} detail="components/ui/button.tsx" />+ <GenericToolRun items={[{ status: state, trace: {+ name: "read_file", family: "read", groupKey: "read", fields: [{ key: "path", value: "webui/src/components/ui/button.tsx" }], collectedSource: false,+ } }]} />+ </ThinkingReasoningShell></>;+}++function FilesPreview() {+ const [state, setState] = useState<"done" | "editing" | "error">("done");+ const [display, setDisplay] = useState<"summary" | "diff" | "collapsed_diff">("diff");+ const [opened, setOpened] = useState("");+ const edit: FileEditSummary = {+ key: "example-edit", path: "src/greeting.ts", added: 1, deleted: 1, approximate: false, binary: false,+ status: state, pending: state === "editing", operation: "edit", error: state === "error" ? "Example edit could not be applied." : undefined,+ diff: { format: "unified", text: '@@ -1,2 +1,2 @@\n-export const greeting = "Hello";\n+export const greeting = "Hello, Nanobot";\n export const ready = true;\n' },+ };+ return <><StatePicker label="File edit state" value={state} options={["done", "editing", "error"]} onChange={setState} />+ <StatePicker label="Diff display" value={display} options={["summary", "diff", "collapsed_diff"]} onChange={setDisplay} />+ <FileEditGroup edits={[edit]} displayMode={display} onOpenFilePreview={setOpened} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">{opened ? `Selected file: ${opened}` : "Select a file reference to exercise its callback."}</p></>;+}++function MediaPreview() {+ return <div className="space-y-6">+ <Sample label="Image gallery · 图片预览">+ <ImageGallery size="compact" images={[{ url: "/brand/nanobot_icon_512.png", name: "Nanobot icon" }, { url: "/brand/nanobot_wordmark.svg", name: "Nanobot wordmark" }]} />+ </Sample>+ <Sample label="Unavailable media · 历史附件缺失">+ <div className="flex flex-wrap gap-3"><AttachmentTile attachment={{ kind: "file", name: "report.txt" }} />+ <AttachmentTile attachment={{ kind: "image", name: "missing-image.png" }} /></div>+ </Sample>+ </div>;+}++function SettingsPreview() {+ const [enabled, setEnabled] = useState(false);+ return <div className="settings-grid space-y-4">+ <SettingsSectionTitle>Example preferences</SettingsSectionTitle>+ <SettingsGroup><SettingsRow title="Keep drafts" description="A shared setting row with a controlled switch.">+ <ToggleButton checked={enabled} onChange={setEnabled} label="Keep drafts" />+ </SettingsRow><SettingsRow title="Project label"><Input aria-label="Settings project label" defaultValue="Nanobot" /></SettingsRow></SettingsGroup>+ <SettingsFeature title="Example capability" enabled={enabled} onChange={setEnabled}>+ <SettingsGroup><SettingsRow title="Notes"><Input aria-label="Capability notes" placeholder="Local preview only" /></SettingsRow></SettingsGroup>+ </SettingsFeature>+ </div>;+}++function FileReferencePreview() {+ const [selected, setSelected] = useState("");+ return <div className="space-y-4"><FileReferenceChip path="src/components/ui/button.tsx" onOpen={setSelected} />+ <p role="status" className="text-sm text-muted-foreground">{selected || "Select the file reference."}</p></div>;+}++const components = "webui/src/components/";+export const sharedExamples: ComponentExample[] = [+ { title: "MarkdownText · 回复排版", files: ["MarkdownText", "MarkdownTextRenderer"], Preview: MarkdownPreview,+ description: "The production streaming renderer, including tables, code and math.", options: "children is Markdown text. streaming controls incomplete content; onOpenFilePreview belongs to the screen.",+ code: '<MarkdownText streaming={running}>{content}</MarkdownText>' },+ { title: "CodeBlock · 代码展示", files: ["CodeBlock", "ViewportCodeRows"], Preview: CodePreview,+ description: "Syntax highlighting, line numbers, clipboard copying, ANSI output and viewport-aware rows.", options: "code and language supply content; showLineNumbers, wrapLongLines and chrome control presentation. Viewport highlighting requires line numbers and unwrapped lines.",+ code: '<CodeBlock language="python" code={source} showLineNumbers />' },+ { title: "DisplayMath · 数学公式", files: ["DisplayMath"], Preview: () => <MarkdownText>{"$$\nE = mc^2\n$$"}</MarkdownText>,+ description: "The shared fitting wrapper around Markdown's rendered display math.", options: "Use MarkdownText for TeX source. DisplayMath itself accepts already-rendered math nodes and scales them to the available width.", code: '<MarkdownText>{"$$\\nE = mc^2\\n$$"}</MarkdownText>' },+ { title: "MessageBubble · 消息", files: ["MessageBubble"], Preview: MessagePreview,+ description: "User and assistant messages, including thinking and delivery states.", options: "message is a UIMessage projected by the chat runtime. Data and network actions remain outside the renderer.",+ code: '<MessageBubble message={{ id: "example", role: "assistant", content: "Hello", createdAt: Date.now() }} />' },+ { title: "Agent activity · 思考与工具活动", files: ["thread/activity/ActivityStep", "thread/activity/ReasoningRow", "thread/activity/ThinkingReasoningShell", "thread/activity/GenericToolRun"], Preview: ActivityPreview,+ description: "Activity primitives composed into a working, completed or failed sequence.", options: "Pass text, status and controlled expansion. The gateway owns tool execution; these components render its projected state.",+ code: '<ReasoningRow text={reasoning} streaming={running} />\n<ActivityStep label="Read source" detail="button.tsx" active={running} />' },+ { title: "FileEditGroup · 文件修改", files: ["thread/activity/FileEditRow", "thread/activity/DiffPair", "thread/activity/DiffSyntaxHighlight"], Preview: FilesPreview,+ description: "File references, line-change counts and expandable diffs.", options: "edits contains display summaries; displayMode selects summary/diff/collapsed_diff; onOpenFilePreview is supplied by the screen.",+ code: '<FileEditGroup edits={edits} displayMode="diff" onOpenFilePreview={openFile} />' },+ { title: "Media · 图片与附件", files: ["ImageGallery", "ImageLightbox", "ZoomableImage", "AttachmentTile"], Preview: MediaPreview,+ description: "Image selection, zoom and navigation, plus unavailable attachment states.", options: "ImageGallery receives image URLs and names. AttachmentTile receives a media attachment; omit the URL for an unavailable file.",+ code: '<ImageGallery images={[{ url: "/brand/nanobot_icon_512.png", name: "Nanobot" }]} />\n<AttachmentTile attachment={{ kind: "file", name: "report.txt" }} />' },+ { title: "FileReferenceChip · 文件引用", files: ["FileReferenceChip"], Preview: FileReferencePreview,+ description: "A file reference with a caller-owned open action.", options: "path supplies the label; onOpen supplies the action. The component does not decide workspace permissions.",+ code: '<FileReferenceChip path="src/app.tsx" onOpen={openFile} />' },+ { title: "Settings composition · 设置组件", files: ["settings/shared/SettingsControls", "settings/shared/SettingsFeature"], Preview: SettingsPreview,+ description: "The actual settings row/group/capability components composed with shared controls.", options: "The containing settings controller owns values and persistence. A gallery callback updates only local preview state.",+ code: '<SettingsGroup><SettingsRow title="Enabled"><ToggleButton checked={enabled} onChange={setEnabled} label="Enabled" /></SettingsRow></SettingsGroup>' },+].map((example) => ({ ...example, files: example.files.map((file) => `${components}${file}.tsx`) }));diff --git a/webui/src/dev/gallery/shell.tsx b/webui/src/dev/gallery/shell.tsxnew file mode 100644index 000000000..d1ce1a085--- /dev/null+++ b/webui/src/dev/gallery/shell.tsx@@ -0,0 +1,283 @@+import { useRef, useState, type ReactNode } from "react";+import { createPortal } from "react-dom";++import { CapabilityMentionToken } from "@/components/CliAppMentionText";+import type { CapabilityMentionSegment } from "@/lib/composer-mention-text";+import { DeleteConfirm } from "@/components/DeleteConfirm";+import { FileActions } from "@/components/FileActions";+import { InlineTokenHighlight, INLINE_TOKEN_HIGHLIGHT_COLOR } from "@/components/InlineTokenHighlight";+import { MessageLinksMenu, useMessageWebLinks } from "@/components/MessageLinksMenu";+import { RenameChatDialog } from "@/components/RenameChatDialog";+import { SessionHandleLabel } from "@/components/SessionHandleLabel";+import { SlashCommandText } from "@/components/SlashCommandText";+import { StartupShell } from "@/components/StartupShell";+import { UserMessageText } from "@/components/UserMessageText";+import { WebLink } from "@/components/WebLink";+import * as ProductIcons from "@/components/icons/product-icons";+import { HostCompatibilityDialog } from "@/components/remote/HostCompatibilityDialog";+import { HostConnectionStatus } from "@/components/remote/HostConnectionStatus";+import type { HostConnectionState } from "@/components/remote/remote-context";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";+import { PaneWorkbench, type WorkbenchPane } from "@/components/workbench/PaneWorkbench";+import type { HostCompatibility, RemoteProfile } from "@/lib/remote-instances";+import type { CliAppInfo, McpPresetInfo, SessionAutomationJob, SessionMention, WorkbenchLayout } from "@/lib/types";+import { cn } from "@/lib/utils";+import { Sample, StatePicker, type ComponentExample } from "./example";++const cliApp: CliAppInfo = {+ name: "nanobot", display_name: "Nanobot", category: "assistant", description: "Local assistant",+ requires: "Python", source: "local", entry_point: "nanobot", install_supported: true,+ installed: true, available: true, status: "installed", skill_installed: true,+ logo_url: "/brand/nanobot_icon_512.png", brand_color: "var(--inline-token-highlight)",+};+const mcpPreset: McpPresetInfo = {+ name: "files", display_name: "Workspace files", category: "files", description: "Workspace files",+ docs_url: "", transport: "stdio", requires: "", note: "", install_supported: true,+ installed: true, configured: true, available: true, status: "configured", required_fields: [],+ connection_summary: "Local files",+};+const sessionMention: SessionMention = {+ id: "gallery-session", name: "design", session_key: "webui:gallery-design", title: "组件设计",+};++function RenamePreview() {+ const [open, setOpen] = useState(false);+ const [title, setTitle] = useState("组件设计");+ return <div className="space-y-4">+ <p className="text-sm">{title}</p>+ <Button variant="outline" onClick={() => setOpen(true)}>重命名会话</Button>+ <RenameChatDialog open={open} title={title} onCancel={() => setOpen(false)}+ onConfirm={(next) => { setTitle(next); setOpen(false); }} />+ <p role="status" className="text-xs text-muted-foreground">保存后更新上方标题。</p>+ </div>;+}++const automations: SessionAutomationJob[] = [+ { id: "gallery-daily", name: "每日项目摘要", enabled: true, schedule: { kind: "cron", expr: "0 9 * * *", tz: "Asia/Shanghai" }, payload: { message: "Summarize project updates" }, state: { next_run_at_ms: Date.UTC(2026, 9, 14, 1) } },+ { id: "gallery-hourly", name: "每小时检查", enabled: false, schedule: { kind: "every", every_ms: 3_600_000 }, payload: { message: "Check updates" }, state: {} },+ { id: "gallery-trigger", name: "发布后检查", enabled: true, schedule: { kind: "local" }, payload: { message: "Check the release", kind: "local_trigger" }, state: {} },+ { id: "gallery-once", name: "一次性提醒", enabled: true, schedule: { kind: "at", at_ms: Date.UTC(2026, 9, 15, 2) }, payload: { message: "Review the result" }, state: { next_run_at_ms: Date.UTC(2026, 9, 15, 2) } },+ { id: "gallery-weekly", name: "每周回顾", enabled: true, schedule: { kind: "every", every_ms: 604_800_000 }, payload: { message: "Review the week" }, state: {} },+];++function DeletePreview() {+ const [scenario, setScenario] = useState<"single" | "multiple" | "automations">("single");+ const [open, setOpen] = useState(false);+ const [deleted, setDeleted] = useState(false);+ return <>+ <StatePicker label="删除场景" value={scenario} options={["single", "multiple", "automations"]}+ onChange={(next) => { setScenario(next); setDeleted(false); }} />+ <Button variant="outline" onClick={() => { setDeleted(false); setOpen(true); }}>打开删除确认</Button>+ <DeleteConfirm open={open} title="组件设计" count={scenario === "multiple" ? 3 : 1}+ automations={scenario === "automations" ? automations : []} onCancel={() => setOpen(false)}+ onConfirm={() => { setDeleted(true); setOpen(false); }} />+ <p role="status" className="mt-4 text-xs text-muted-foreground">{deleted ? "已确认删除示例。" : "选择单个、批量或带自动任务的会话。"}</p>+ </>;+}++function InlineTokensPreview() {+ const [command, setCommand] = useState("/status");+ const [handle, setHandle] = useState("gallery-session");+ return <div className="space-y-5">+ <Sample label="命令文本"><Input aria-label="命令文本" value={command} onChange={(event) => setCommand(event.target.value)} />+ <p className="text-sm">运行 <SlashCommandText command={command} /> 查看状态。</p></Sample>+ <Sample label="会话标识"><Input aria-label="会话标识" value={handle} onChange={(event) => setHandle(event.target.value)} />+ <p className="text-sm">继续 <SessionHandleLabel id={handle}>@design</SessionHandleLabel> 中的工作。</p></Sample>+ <Sample label="共享高亮"><p className="text-sm">使用 <InlineTokenHighlight color={INLINE_TOKEN_HIGHLIGHT_COLOR} title="Skill: review">review</InlineTokenHighlight> 检查修改。</p></Sample>+ </div>;+}++function SessionLinksPreview({ children }: { children: ReactNode }) {+ const [selected, setSelected] = useState(false);+ return <div className="space-y-4" onClick={(event) => {+ if (!(event.target instanceof Element)) return;+ const link = event.target.closest<HTMLAnchorElement>('a[href^="#/chat/"]');+ if (!link) return;+ event.preventDefault();+ setSelected(true);+ }}>+ {children}+ <p role="status" className="text-xs text-muted-foreground">{selected ? "已选择会话:组件设计。" : "选择会话引用查看反馈。"}</p>+ </div>;+}++function UserTextPreview() {+ const [text, setText] = useState("用 $review 检查 @nanobot 的修改,参考 @design 和 @files。");+ return <SessionLinksPreview>+ <label className="grid gap-2 text-xs text-muted-foreground">消息文本+ <Textarea value={text} onChange={(event) => setText(event.target.value)} />+ </label>+ <p className="whitespace-pre-wrap text-sm leading-7"><UserMessageText text={text} cliApps={[cliApp]}+ mcpPresets={[mcpPreset]} sessionMentions={[sessionMention]} /></p>+ </SessionLinksPreview>;+}++function CapabilityTokensPreview() {+ const [variant, setVariant] = useState<"message" | "composer">("message");+ const segments: Array<Exclude<CapabilityMentionSegment, { kind: "text" }>> = [+ { kind: "cli", text: "@nanobot", app: cliApp },+ { kind: "mcp", text: "@files", preset: mcpPreset },+ { kind: "session", text: "@design", mention: sessionMention },+ ];+ return <SessionLinksPreview>+ <StatePicker label="引用位置" value={variant} options={["message", "composer"]} onChange={setVariant} />+ <div className="flex flex-wrap gap-6 text-sm leading-7">{segments.map((segment) =>+ <CapabilityMentionToken key={segment.kind} segment={segment} variant={variant} />)}</div>+ </SessionLinksPreview>;+}++function ProductIconsPreview() {+ const [size, setSize] = useState<"16" | "20" | "24">("20");+ const [selected, setSelected] = useState("ConversationIcon");+ return <>+ <StatePicker label="图标尺寸" value={size} options={["16", "20", "24"]} onChange={setSize} />+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-6">{Object.entries(ProductIcons).map(([name, Icon]) =>+ <button key={name} type="button" aria-pressed={selected === name} onClick={() => setSelected(name)}+ className={cn("flex min-w-0 flex-col items-center gap-2 rounded-control p-3 text-muted-foreground hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", selected === name && "bg-muted text-foreground")}>+ <Icon size={Number(size)} /><span className="max-w-full break-all text-center text-[10px] leading-4">{name.replace(/Icon$/, "")}</span>+ </button>)}</div>+ <p role="status" className="mt-4 text-xs text-muted-foreground">已选择:{selected}</p>+ </>;+}++function StartupPreview() {+ return <div className="gallery-startup-preview h-80 overflow-hidden rounded-panel border"><StartupShell embedded /></div>;+}++function FileActionsPreview() {+ const [scope, setScope] = useState<"workspace" | "outside" | "unresolved">("workspace");+ const path = "src/app.tsx";+ return <>+ <StatePicker label="文件范围" value={scope} options={["workspace", "outside", "unresolved"]} onChange={setScope} />+ <FileActions path={path} metadata={scope === "unresolved" ? undefined : {+ path: scope === "workspace" ? "D:/workspace/nanobot/src/app.tsx" : "D:/documents/report.tsx",+ relative_path: scope === "workspace" ? path : null,+ }}><Button variant="outline">{path}</Button></FileActions>+ <p className="mt-4 text-xs text-muted-foreground">右键打开复制菜单,也可聚焦文件后按 Shift+F10。</p>+ </>;+}++function WebLinksPreview() {+ const [open, setOpen] = useState(false);+ const [display, setDisplay] = useState<"compact" | "expanded">("compact");+ const message = useRef<HTMLDivElement>(null);+ const links = useMessageWebLinks(message, open);+ return <div className="space-y-4">+ <StatePicker label="链接菜单宽度" value={display} options={["compact", "expanded"]} onChange={setDisplay} />+ <div ref={message} className="text-sm leading-7"><p data-assistant-selectable>+ 查看 <WebLink href={`${window.location.origin}/gallery.html`} className="underline underline-offset-4">组件画廊</WebLink>+ {" 和 "}<WebLink href={`${window.location.origin}/brand/nanobot_icon_512.png`} className="underline underline-offset-4">品牌图片</WebLink>。+ </p></div>+ <Button variant="outline" onClick={() => setOpen((value) => !value)}>{open ? "关闭链接菜单" : "查看消息链接"}</Button>+ {open && links.length > 0 ? <div className="rounded-control border p-1">+ <MessageLinksMenu links={links} onBack={() => setOpen(false)} onClose={() => setOpen(false)} expanded={display === "expanded"} />+ </div> : null}+ <p className="text-xs text-muted-foreground">右键链接可复制地址;消息菜单从实际渲染的链接中收集条目。</p>+ </div>;+}++const initialPanes: WorkbenchPane[] = [+ { key: "pane-1", title: "组件设计" }, { key: "pane-2", title: "实现" }, { key: "pane-3", title: "验证" },+];++function WorkbenchPreview() {+ const [panes, setPanes] = useState(initialPanes);+ const [active, setActive] = useState("pane-1");+ const [layout, setLayout] = useState<WorkbenchLayout>("columns");+ const [ratios, setRatios] = useState<number[]>([]);+ return <>+ <StatePicker label="窗格布局" value={layout} options={["columns", "rows", "grid", "bsp", "main-stack"]}+ onChange={(next) => { setLayout(next); setRatios([]); }} />+ <div className="h-[28rem] overflow-hidden rounded-panel border">+ <PaneWorkbench panes={panes} activePaneKey={active} layout={layout} showLayoutControl+ addPaneDisabled={panes.length >= 4} addPaneDisabledLabel="最多四个窗格"+ onActivatePane={setActive} onLayoutChange={(next) => { setLayout(next); setRatios([]); }}+ onAddPane={() => {+ const next = { key: `pane-${panes.length + 1}`, title: "补充笔记" };+ setPanes([...panes, next]); setActive(next.key);+ }}+ onPaneOrderChange={(keys) => setPanes(keys.flatMap((key) => panes.filter((pane) => pane.key === key)))}+ splitRatios={ratios} onSplitRatiosChange={setRatios}+ renderPane={(pane, context) => {+ const header = <div className="pointer-events-auto flex h-10 items-center justify-between gap-2 px-3 text-xs">+ <span>{pane.title}</span>{context.headerActions}+ </div>;+ return <div className="flex min-w-0 flex-1 flex-col gap-3 p-3 pb-8">+ {context.active && context.headerPortalTarget ? createPortal(header, context.headerPortalTarget) : context.active ? header : <p className="h-10 content-center text-xs text-muted-foreground">{pane.title}</p>}+ <label className="grid gap-2 text-xs text-muted-foreground">{pane.title}笔记+ <Textarea defaultValue={`在${pane.title}窗格中编辑笔记。`} /></label>+ <p className="text-xs text-muted-foreground">{context.active ? "当前窗格" : "选择此窗格以激活"}</p>+ </div>;+ }} />+ </div>+ <p role="status" className="mt-4 text-xs text-muted-foreground">当前:{panes.find((pane) => pane.key === active)?.title}。拖动底部手柄移动窗格,拖动边界调整尺寸。</p>+ </>;+}++function ConnectionPreview() {+ const [state, setState] = useState<HostConnectionState>("open");+ return <>+ <StatePicker label="连接状态" value={state} options={["open", "closed", "connecting", "error"]} onChange={setState} />+ <div className="flex flex-wrap gap-8"><Sample label="状态与文字"><HostConnectionStatus state={state} /></Sample>+ <Sample label="紧凑显示"><HostConnectionStatus state={state} compact /></Sample></div>+ </>;+}++function CompatibilityPreview() {+ const [status, setStatus] = useState<HostCompatibility["status"] | "unchecked">("compatible");+ const [open, setOpen] = useState(false);+ const profile: RemoteProfile = {+ id: "gallery-host", name: "开发主机", host: "dev.example", port: 22, ssh_config: "", identity_file: "",+ config_path: "~/.nanobot/config.json", runtime_user: "developer", connected: false,+ compatibility: status === "unchecked" ? undefined : {+ status, client_version: "0.3.0", host_version: status === "update_host" ? "0.2.0" : status === "update_client" ? "0.4.0" : "0.3.0",+ },+ };+ return <>+ <StatePicker label="版本兼容状态" value={status} options={["compatible", "update_host", "update_client", "unknown", "unchecked"]} onChange={setStatus} />+ <Button variant="outline" onClick={() => setOpen(true)}>查看兼容详情</Button>+ <HostCompatibilityDialog profile={open ? profile : undefined} clientVersion="0.3.0" onClose={() => setOpen(false)} />+ </>;+}++const components = "webui/src/components/";+export const shellExamples: ComponentExample[] = [+ { title: "RenameChatDialog · 重命名", files: ["RenameChatDialog"], Preview: RenamePreview,+ description: "打开真实重命名对话框,编辑标题并保存。", options: "open 控制显示,title 设置初值,onConfirm 接收去除两端空白的标题。空标题无法保存。",+ code: '<RenameChatDialog open={open} title={title} onCancel={close} onConfirm={rename} />' },+ { title: "DeleteConfirm · 删除确认", files: ["DeleteConfirm"], Preview: DeletePreview,+ description: "切换单个、批量和关联自动任务的删除确认。", options: "count 控制批量文案;automations 展示关联任务、计划与下次运行时间。确认按钮调用 onConfirm。",+ code: '<DeleteConfirm open={open} title="组件设计" count={1} automations={jobs} onCancel={close} onConfirm={remove} />' },+ { title: "Inline tokens · 命令与会话标识", files: ["SlashCommandText", "InlineTokenHighlight", "SessionHandleLabel"], Preview: InlineTokensPreview,+ description: "输入命令与会话标识,观察高亮与稳定的会话颜色。", options: "SlashCommandText 接收 command;InlineTokenHighlight 接收 color 和内容;SessionHandleLabel 根据 id 生成颜色。",+ code: '<SlashCommandText command="/status" />\n<SessionHandleLabel id={session.id}>@design</SessionHandleLabel>\n<InlineTokenHighlight color="var(--inline-token-highlight)">review</InlineTokenHighlight>' },+ { title: "UserMessageText · 消息引用", files: ["UserMessageText"], Preview: UserTextPreview,+ description: "编辑消息,预览技能、应用、MCP 和会话引用。", options: "text 为原始消息;cliApps、mcpPresets 与 sessionMentions 提供可解析引用。技能使用 $name,其他引用使用 @name。",+ code: '<UserMessageText text={text} cliApps={apps} mcpPresets={presets} sessionMentions={sessions} />' },+ { title: "CapabilityMentionToken · 应用引用", files: ["CliAppMentionText"], Preview: CapabilityTokensPreview,+ description: "比较应用、MCP 与会话引用在输入框和消息中的样式。", options: "segment 指定 cli、mcp 或 session 及其元数据;variant 选择 composer 或 message。示例使用本地品牌图片。",+ code: '<CapabilityMentionToken segment={{ kind: "cli", text: "@nanobot", app }} variant="message" />' },+ { title: "Product icons · 产品图标", files: ["icons/product-icons"], Preview: ProductIconsPreview,+ description: "浏览实际产品图标,切换尺寸并选择高亮状态。", options: "图标接受 LucideProps,例如 size、strokeWidth、className。颜色继承 currentColor,按钮提供可访问的动作名称。",+ code: '<ConversationIcon size={20} />\n<SettingsIcon className="text-muted-foreground" />' },+ { title: "StartupShell · 启动占位", files: ["StartupShell"], Preview: StartupPreview,+ description: "预览应用连接时的安静占位布局。", options: "embedded 使用 section,其余情况使用 main。组件持续提供 aria-busy 与加载状态;占位样式来自应用入口。",+ code: '<StartupShell embedded />' },+ { title: "FileActions · 文件菜单", files: ["FileActions"], Preview: FileActionsPreview,+ description: "右键文件,体验完整路径、相对路径和引用文本的复制菜单。", options: "path 为引用文本;metadata 提供完整路径与可选相对路径。画廊直接提供元数据,无需加载文件。",+ code: '<FileActions path="src/app.tsx" metadata={{ path: "D:/workspace/src/app.tsx", relative_path: "src/app.tsx" }}><Button>app.tsx</Button></FileActions>' },+ { title: "Web links · 链接菜单", files: ["WebLink", "MessageLinksMenu"], Preview: WebLinksPreview,+ description: "打开真实链接菜单,选择消息中的链接并复制地址。", options: "WebLink 接收链接属性;useMessageWebLinks 收集消息中实际渲染的链接。MessageLinksMenu 接收条目、返回与关闭回调,expanded 控制宽度。示例链接均指向本地画廊资源。",+ code: '<WebLink href={url}>组件画廊</WebLink>\nconst links = useMessageWebLinks(messageRef, open);\n<MessageLinksMenu links={links} onBack={close} onClose={close} expanded />' },+ { title: "PaneWorkbench · 多窗格", files: ["workbench/PaneWorkbench"], Preview: WorkbenchPreview,+ description: "切换布局、激活窗格、添加窗格并调整位置与尺寸。", options: "panes、activePaneKey、layout 与 splitRatios 由调用方控制。renderPane 提供内容;回调将变更写回本地示例状态。窄屏自动显示当前窗格。",+ code: '<PaneWorkbench panes={panes} activePaneKey={active} layout={layout} showLayoutControl onActivatePane={setActive} onAddPane={addPane} onLayoutChange={setLayout} onPaneOrderChange={reorder} renderPane={renderPane} />' },+ { title: "HostConnectionStatus · 连接状态", files: ["remote/HostConnectionStatus"], Preview: ConnectionPreview,+ description: "切换已连接、断开、连接中和出错状态。", options: "state 控制图标与文字,compact 隐藏可见文字并保留可访问状态和悬浮标题。",+ code: '<HostConnectionStatus state="connecting" />\n<HostConnectionStatus state="open" compact />' },+ { title: "HostCompatibilityDialog · 版本兼容", files: ["remote/HostCompatibilityDialog"], Preview: CompatibilityPreview,+ description: "切换兼容检查结果,查看版本、准备说明和升级指南入口。", options: "profile 存在时打开对话框;compatibility 指定报告状态与版本。onClose 由调用方关闭;此组件只展示信息。",+ code: '<HostCompatibilityDialog profile={selectedProfile} clientVersion="0.3.0" onClose={close} />' },+].map((example) => ({ ...example, files: example.files.map((file) => `${components}${file}.tsx`) }));diff --git a/webui/src/dev/gallery/standalone.tsx b/webui/src/dev/gallery/standalone.tsxnew file mode 100644index 000000000..6f8ad5181--- /dev/null+++ b/webui/src/dev/gallery/standalone.tsx@@ -0,0 +1,130 @@+import { useState } from "react";++import { ChatList } from "@/components/ChatList";+import { ConnectionBadge } from "@/components/ConnectionBadge";+import { LanguageSwitcher } from "@/components/LanguageSwitcher";+import { SidebarResizeHandle } from "@/components/SidebarResizeHandle";+import { HostSwitcherView } from "@/components/remote/HostSwitcherView";+import type { HostPicker } from "@/components/remote/host-navigation";+import { Button } from "@/components/ui/button";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { LinearAvatar } from "../../../../nanobot/channels/linear/webui/LinearAvatar";+import { LinearHelpContent } from "../../../../nanobot/channels/linear/webui/LinearHelpContent";+import { LinearSecretField } from "../../../../nanobot/channels/linear/webui/LinearSecretField";+import { WebSocketIcon } from "../../../../nanobot/channels/websocket/webui/WebSocketIcon";+import type { ChatSummary, ConnectionStatus } from "@/lib/types";+import { Sample, StatePicker, type ComponentExample } from "./example";++function ConnectionPreview() {+ const [status, setStatus] = useState<ConnectionStatus>("open");+ return <><StatePicker label="连接状态" value={status} options={["idle", "connecting", "open", "reconnecting", "closed", "error"]} onChange={setStatus} />+ <div className="flex items-center gap-3"><ConnectionBadge status={status} /><span className="text-sm">{status}</span></div></>;+}++function HostPickerPreview() {+ const [mode, setMode] = useState<"ready" | "pending" | "offline" | "collapsed">("ready");+ const [currentId, setCurrentId] = useState<string | null>(null);+ const [action, setAction] = useState("");+ const profiles: HostPicker["profiles"] = [+ { id: "gallery-development", name: "开发主机", host: "[email protected]", state: "open" },+ { id: "gallery-build", name: "构建主机", host: "[email protected]", state: "closed" },+ ];+ const selected = profiles.find((profile) => profile.id === currentId);+ const picker: HostPicker = {+ kind: "shell", name: selected?.name ?? "本机", hostname: selected?.host ?? "gallery", localName: "gallery",+ currentId, profiles, recentIds: [], pending: mode === "pending" ? { id: profiles[0].id, name: profiles[0].name } : null,+ error: mode === "offline" ? "示例主机已断开。" : "", offline: mode === "offline",+ select: (id) => { setCurrentId(id); setMode("ready"); }, manage: () => setAction("打开连接管理"),+ cancel: () => { setMode("ready"); setAction("已取消示例切换"); }, clearError: () => setMode("ready"), restoreFocus: () => {},+ };+ return <><StatePicker label="主机菜单状态" value={mode} options={["ready", "pending", "offline", "collapsed"]} onChange={setMode} />+ <div className="max-w-sm rounded-panel bg-sidebar p-4"><HostSwitcherView picker={picker} status="open" collapsed={mode === "collapsed"} /></div>+ <p role="status" className="mt-4 text-sm text-muted-foreground">{action || `预览中的主机:${picker.name}`}</p></>;+}++const initialSessions: ChatSummary[] = [+ { key: "websocket:gallery-components", chatId: "gallery-components", channel: "websocket", title: "组件设计", preview: "模型选择、消息输入和设置表单。",+ createdAt: "2026-10-01T12:00:00Z", updatedAt: "2026-10-13T08:00:00Z", handle: { id: "gallery-components", name: "design" } },+ { key: "websocket:gallery-tests", chatId: "gallery-tests", channel: "websocket", title: "验证交互", preview: "检查错误状态与键盘操作。",+ createdAt: "2026-10-02T12:00:00Z", updatedAt: "2026-10-13T09:00:00Z", handle: { id: "gallery-tests", name: "tests" } },+];++function ChatsPreview() {+ const [sessions, setSessions] = useState(initialSessions);+ const [active, setActive] = useState<string | null>(initialSessions[0].key);+ const [pinned, setPinned] = useState<string[]>([]);+ const [archived, setArchived] = useState<string[]>([]);+ const [mode, setMode] = useState<"ready" | "loading" | "empty" | "archived">("ready");+ const [action, setAction] = useState("");+ const toggle = (keys: string[], key: string) => keys.includes(key) ? keys.filter((value) => value !== key) : [...keys, key];+ return <><StatePicker label="会话列表状态" value={mode} options={["ready", "loading", "empty", "archived"]} onChange={setMode} />+ <div className="flex h-80 max-w-sm flex-col rounded-panel bg-sidebar p-2"><ChatList sessions={mode === "empty" ? [] : sessions}+ activeKey={active} onSelect={setActive} pinnedKeys={pinned} archivedKeys={archived} showArchived={mode === "archived"}+ showPreviews showTimestamps loading={mode === "loading"}+ onTogglePin={(key) => setPinned(toggle(pinned, key))} onToggleArchive={(key) => setArchived(toggle(archived, key))}+ onRequestDelete={(key) => setSessions((items) => items.filter((item) => item.key !== key))}+ onRequestRename={(_, label) => setAction(`选择重命名:${label}`)} /></div>+ <p role="status" className="mt-4 text-sm text-muted-foreground">{action || `选择的会话:${active ?? "无"}`}</p></>;+}++function SidebarResizePreview() {+ const [width, setWidth] = useState(260);+ const [open, setOpen] = useState(true);+ const [dragging, setDragging] = useState(false);+ return <div className="space-y-4"><div className="relative flex h-72 overflow-hidden rounded-panel border">+ <aside id="main-sidebar" className="relative shrink-0 bg-sidebar p-4" style={{ width: open ? width : 56 }}>+ {open ? <p className="text-sm text-muted-foreground">侧栏内容</p> : null}+ <SidebarResizeHandle width={width} open={open} onResize={(next, expanded) => { setWidth(next); setOpen(expanded); }} onDraggingChange={setDragging} />+ </aside><div className="min-w-0 flex-1 p-4 text-sm text-muted-foreground">拖动分隔条,或聚焦后使用方向键、Home、End 和 Enter。</div>+ </div><p role="status" className="text-sm text-muted-foreground">{open ? `${width}px` : "已收起"}{dragging ? " · 正在拖动" : ""}</p></div>;+}++function ChannelMarksPreview() {+ const [name, setName] = useState<"Nanobot" | "研发">("Nanobot");+ return <><StatePicker label="头像名称" value={name} options={["Nanobot", "研发"]} onChange={setName} />+ <div className="flex items-start gap-8"><Sample label="成员头像"><LinearAvatar name={name} /></Sample>+ <Sample label="工作区图标"><LinearAvatar name={name} workspace /></Sample><Sample label="WebSocket"><WebSocketIcon /></Sample></div></>;+}++function SecretPreview() {+ const [mode, setMode] = useState<"new" | "saved" | "disabled" | "error">("new");+ const [configured, setConfigured] = useState(false);+ return <><StatePicker label="密钥状态" value={mode} options={["new", "saved", "disabled", "error"]}+ onChange={(next) => { setMode(next); setConfigured(next === "saved"); }} />+ <LinearSecretField field={{ key: "api_key", label: "API Key", secret: true }} configured={configured} disabled={mode === "disabled"}+ onSave={async () => { if (mode === "error") throw new Error("Example save failed"); setConfigured(true); }} />+ <p className="mt-4 text-xs text-muted-foreground">输入示例文本并保存,或切换错误状态检查草稿保留。</p></>;+}++function ChannelHelpPreview() {+ return <DropdownMenu><DropdownMenuTrigger asChild><Button variant="outline">打开频道帮助</Button></DropdownMenuTrigger>+ <DropdownMenuContent><LinearHelpContent /><DropdownMenuItem>关闭</DropdownMenuItem></DropdownMenuContent></DropdownMenu>;+}++const components = "webui/src/components/";+export const standaloneExamples: ComponentExample[] = [+ { title: "ConnectionBadge · 连接指示", files: [`${components}ConnectionBadge.tsx`], Preview: ConnectionPreview,+ description: "切换连接状态,查看颜色、动画和可访问状态文字。", options: "status 来自调用方。连接订阅由页面容器维护。",+ code: '<ConnectionBadge status={status} />' },+ { title: "HostSwitcherView · 主机菜单", files: [`${components}remote/HostSwitcherView.tsx`], Preview: HostPickerPreview,+ description: "打开主机菜单,选择本机或示例主机,并切换待连接、断开和收起状态。", options: "picker 提供主机显示数据与操作回调;status 是当前连接状态。生产 HostSwitcher 负责订阅客户端。",+ code: '<HostSwitcherView picker={picker} status="open" collapsed={false} />' },+ { title: "ChatList · 会话列表", files: [`${components}ChatList.tsx`, `${components}SidebarSelectionHighlight.tsx`], Preview: ChatsPreview,+ description: "选择会话,打开操作菜单,试用置顶、归档和删除。", options: "sessions、activeKey 和已置顶/归档的 key 由调用方提供。各操作通过回调更新示例列表。",+ code: '<ChatList sessions={sessions} activeKey={active} onSelect={setActive} onTogglePin={pin} onToggleArchive={archive} onRequestDelete={remove} onRequestRename={rename} />' },+ { title: "SidebarResizeHandle · 侧栏尺寸", files: [`${components}SidebarResizeHandle.tsx`], Preview: SidebarResizePreview,+ description: "用鼠标或键盘调整侧栏宽度并收起或展开。", options: "width 与 open 是受控状态;onResize 更新尺寸与展开状态;onDraggingChange 通知拖动状态。",+ code: '<SidebarResizeHandle width={width} open={open} onResize={resize} onDraggingChange={setDragging} />' },+ { title: "LanguageSwitcher · 界面语言", files: [`${components}LanguageSwitcher.tsx`], Preview: LanguageSwitcher,+ description: "切换画廊内生产组件使用的界面语言。", options: "使用应用已有 i18n 与浏览器语言偏好,不需要 gateway。顶部语言选择器使用同一个组件。",+ code: '<LanguageSwitcher />' },+ { title: "Channel marks · 频道标识", files: ["nanobot/channels/linear/webui/LinearAvatar.tsx", "nanobot/channels/websocket/webui/WebSocketIcon.tsx"], Preview: ChannelMarksPreview,+ description: "查看成员头像缺省文字、工作区图标和 WebSocket 标识。", options: "LinearAvatar 接收 name、url 和 workspace;无有效图片时显示缺省文字或图标。",+ code: '<LinearAvatar name="Nanobot" />\n<LinearAvatar name="Nanobot" workspace />\n<WebSocketIcon />' },+ { title: "LinearSecretField · 密钥编辑", files: ["nanobot/channels/linear/webui/LinearSecretField.tsx"], Preview: SecretPreview,+ description: "编辑、显示、保存与替换密钥,检查保存失败时的输入保留。", options: "configured 是已保存状态,onSave 负责持久化。画廊回调仅更新本地状态。",+ code: '<LinearSecretField field={field} configured={configured} disabled={false} onSave={save} />' },+ { title: "LinearHelpContent · 频道帮助", files: ["nanobot/channels/linear/webui/LinearHelpContent.tsx"], Preview: ChannelHelpPreview,+ description: "在实际下拉菜单中查看频道帮助内容。", options: "内容使用频道的现有翻译,菜单容器由调用方提供。",+ code: '<DropdownMenuContent><LinearHelpContent /></DropdownMenuContent>' },+];diff --git a/webui/src/tests/automation-chat-binding.test.tsx b/webui/src/tests/automation-chat-binding.test.tsxindex 658c1304a..7489ee174 100644--- a/webui/src/tests/automation-chat-binding.test.tsx+++ b/webui/src/tests/automation-chat-binding.test.tsx@@ -210,6 +210,23 @@ it("keeps the current chat visible when discovery fails and permits a retry", asexpect(fetchAutomationChats).toHaveBeenCalledTimes(2);});+it("aborts discovery for the previous task and ignores its delayed chat choices", async () => {+ let first!: (value: AutomationChatsPayload) => void;+ let second!: (value: AutomationChatsPayload) => void;+ vi.mocked(fetchAutomationChats).mockImplementationOnce(() => new Promise(resolve => { first = resolve; }));+ vi.mocked(fetchAutomationChats).mockImplementationOnce(() => new Promise(resolve => { second = resolve; }));+ const { rerender } = render(<AutomationDetailDialog {...props} job={job} onChangeChat={vi.fn()} />);+ const oldSignal = vi.mocked(fetchAutomationChats).mock.calls[0][2]!;+ rerender(<AutomationDetailDialog {...props} job={{ ...job, id: "another-task", chat_binding_revision: "rev-next" }} onChangeChat={vi.fn()} />);+ expect(oldSignal.aborted).toBe(true);+ await act(async () => first({ ...choices, current: target }));+ expect(screen.getByRole("combobox", { name: "Run in chat" })).toBeDisabled();+ expect(screen.getByRole("combobox", { name: "Run in chat" })).not.toHaveTextContent("Product team");+ await act(async () => second({ ...choices, current: target, revision: "rev-next" }));+ expect(screen.getByRole("combobox", { name: "Run in chat" })).toHaveTextContent("Product team");+ expect(screen.getByRole("combobox", { name: "Run in chat" })).toBeEnabled();+});+const webTarget = { ...target, channel: "websocket" };const namedSessions: ChatSummary[] = [source, webTarget].map((chat) => ({key: `websocket:${chat.id}`, channel: "websocket", chatId: chat.id,diff --git a/webui/src/tests/automation-run-dialog.test.tsx b/webui/src/tests/automation-run-dialog.test.tsxindex e69cdfb0c..3f021c22b 100644--- a/webui/src/tests/automation-run-dialog.test.tsx+++ b/webui/src/tests/automation-run-dialog.test.tsx@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { AutomationRunDialog } from "@/components/settings/system/AutomationRunDialog";+import { AutomationRunDialogView } from "@/components/settings/system/AutomationRunDialogView";import { fetchAutomationRunResult } from "@/lib/api";import i18n from "@/i18n";import type { SessionAutomationJob } from "@/lib/types";@@ -25,6 +26,21 @@ beforeEach(async () => {afterEach(cleanup);describe("Automation run response", () => {+ it("renders caller-owned results and delegates retry without loading a run", async () => {+ const retry = vi.fn();+ const { rerender } = render(<AutomationRunDialogView job={job} run={run} locale="en" open+ result={{ status: "error", response: null }} onRetry={retry}+ onOpenChange={props.onOpenChange} onCloseAutoFocus={props.onCloseAutoFocus} />);+ await userEvent.click(screen.getByRole("button", { name: "Retry" }));+ expect(retry).toHaveBeenCalledTimes(1);+ expect(fetchResult).not.toHaveBeenCalled();+ rerender(<AutomationRunDialogView job={job} run={run} locale="en" open+ result={{ status: "loaded", response: "A supplied result" }} onRetry={retry}+ onOpenChange={props.onOpenChange} onCloseAutoFocus={props.onCloseAutoFocus} />);+ expect(await screen.findByText("A supplied result")).toBeVisible();+ expect(fetchResult).not.toHaveBeenCalled();+ });+it("loads only the selected run and renders its Markdown response", async () => {let complete!: (value: { response: string }) => void;fetchResult.mockReturnValue(new Promise((resolve) => { complete = resolve; }));diff --git a/webui/src/tests/component-gallery.test.tsx b/webui/src/tests/component-gallery.test.tsxnew file mode 100644index 000000000..9570118b4--- /dev/null+++ b/webui/src/tests/component-gallery.test.tsx@@ -0,0 +1,200 @@+import { resolve } from "node:path";+import { cwd } from "node:process";+import { act, cleanup, render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++import { Gallery, examples } from "@/dev/gallery/Gallery";+import { componentInventory } from "@/dev/gallery/inventory-plugin";+import { foundationPath } from "@/dev/gallery/inventory";+import { registeredChannelUiContributions } from "@/channel-plugins/registry";++const inventory = componentInventory(resolve(cwd(), ".."));++beforeEach(() => {+ window.history.replaceState({}, "", "/gallery.html");+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++it("indexes shared component exports and their application and channel consumers", () => {+ const toggle = inventory.find((item) => item.path === `${foundationPath}toggle-button.tsx`);+ expect(toggle?.exports).toContain("ToggleButton");+ expect(toggle?.usedBy).toEqual(expect.arrayContaining([+ "webui/src/components/thread/WorkspaceControls.tsx",+ "nanobot/channels/linear/webui/LinearMemberAccessView.tsx",+ ]));+ expect(inventory.find((item) => item.path === "nanobot/channels/linear/webui/LinearMemberAccess.tsx")?.group)+ .toBe("Channels / linear");+ expect(inventory.find((item) => item.path === "nanobot/channels/linear/webui/index.tsx")?.exports).toContain("default");+ expect(inventory.find((item) => item.path === "webui/src/components/MarkdownTextRenderer.tsx")?.exports).toContain("default");+});++it("provides a live example for every foundation source and resolves every documented example source", () => {+ const previewed = new Set(examples.flatMap((example) => example.files));+ for (const item of inventory.filter((source) => source.group === "Foundations")) {+ expect(previewed.has(item.path), `Missing foundation example: ${item.path}`).toBe(true);+ }+ const known = new Set(inventory.map((source) => source.path));+ for (const file of previewed) expect(known.has(file), `Unknown example source: ${file}`).toBe(true);+});++it("finds a shared component by its name and renders its working variants", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));+ render(<Gallery />);+ await screen.findByRole("heading", { name: "Button · 按钮" });+ await userEvent.type(screen.getByRole("searchbox", { name: "Search components" }), "toggle-button");+ expect(screen.getByRole("link", { name: /toggle-button/ })).toHaveAttribute("href", expect.stringContaining("toggle-button"));+ await userEvent.click(screen.getByRole("button", { name: "destructive", exact: true }));+ expect(screen.getByText("Button clicks: 1")).toBeVisible();+ expect(screen.getByRole("button", { name: "Unavailable", exact: true })).toBeDisabled();+});++it("lets the developer retry a failed inventory request", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce({ ok: false })+ .mockResolvedValueOnce({ ok: true, json: async () => inventory }));+ render(<Gallery />);+ expect(await screen.findByRole("alert")).toHaveTextContent("Could not load the inventory");+ await userEvent.click(screen.getByRole("button", { name: "Refresh inventory" }));+ expect(await screen.findByRole("heading", { name: "Button · 按钮" })).toBeVisible();+});++it("covers every registered channel and its presentation components", () => {+ const previewed = new Set(examples.flatMap((example) => example.files));+ for (const { channel, webui } of registeredChannelUiContributions()) {+ const entry = `nanobot/channels/${channel}/${webui}`;+ expect(inventory.find((source) => source.path === entry)?.exports).toContain("default");+ expect(previewed.has(entry), `Missing channel entry preview: ${channel}`).toBe(true);+ }+ for (const source of inventory.filter((item) => item.path.startsWith("nanobot/channels/"))) {+ const hasView = inventory.some((view) => previewed.has(view.path) && view.usedBy.includes(source.path));+ expect(previewed.has(source.path) || hasView, `Missing channel component preview: ${source.path}`).toBe(true);+ }+});++it("starts with working previews and lets the developer inspect source-only modules", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));+ render(<Gallery />);+ await screen.findByRole("heading", { name: "Button · 按钮" });+ expect(screen.queryByRole("link", { name: /SettingsPage/ })).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "All source · 源码" }));+ const sourceLink = screen.getByRole("link", { name: /SettingsPage Source only/ });+ // happy-dom does not follow anchor navigation or emit the browser's hashchange.+ act(() => {+ window.location.hash = sourceLink.getAttribute("href")!;+ window.dispatchEvent(new HashChangeEvent("hashchange"));+ });+ expect(await screen.findByRole("heading", { name: "Source only · 暂无独立预览" })).toBeVisible();+ expect(screen.getByRole("link", { name: /Settings composition/ })).toBeVisible();++ await userEvent.click(screen.getByRole("button", { name: "Previews · 预览" }));+ expect(await screen.findByRole("region", { name: "Component preview" })).toBeVisible();+ expect(screen.queryByRole("heading", { name: "Source only · 暂无独立预览" })).not.toBeInTheDocument();+});++it("opens bookmarked source entries and offers all source when a preview search has no match", async () => {+ const source = "webui/src/components/settings/SettingsView.tsx";+ window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => inventory }));+ render(<Gallery />);+ expect(await screen.findByRole("heading", { name: "SettingsView" })).toBeVisible();+ expect(screen.getByRole("link", { name: /^SettingsView Source only/ })).toHaveAttribute("aria-current", "page");++ await userEvent.click(screen.getByRole("button", { name: "Previews · 预览" }));+ await userEvent.type(screen.getByRole("searchbox", { name: "Search components" }), source);+ expect(screen.getByText("No matching previews.")).toBeVisible();+ await userEvent.click(screen.getByRole("button", { name: "Search all source" }));+ expect(screen.getByRole("link", { name: /^SettingsView Source only/ })).toBeVisible();+});++it("submits a message through the actual composer using only local preview state", async () => {+ const source = "webui/src/components/thread/ThreadComposer.tsx";+ window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });+ vi.stubGlobal("fetch", fetch);+ render(<Gallery />);+ const input = await screen.findByRole("textbox", { name: "示例消息" });+ await userEvent.type(input, "Try the real composer{Enter}");+ expect(await screen.findByText("提交内容:Try the real composer")).toBeVisible();+ expect(input).toHaveValue("");+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");+});++it("edits a pairing route without mounting a client or making a gateway mutation", async () => {+ const source = "webui/src/components/remote/PairRouteSettingsView.tsx";+ window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });+ vi.stubGlobal("fetch", fetch);+ render(<Gallery />);+ await screen.findByRole("heading", { name: "PairRouteSettingsView · 配对路由" });+ const preview = within(screen.getByRole("region", { name: "Component preview" }));+ expect(preview.getByRole("button", { name: "Save changes" })).toBeDisabled();+ await userEvent.click(preview.getByRole("combobox", { name: "Network route" }));+ await userEvent.click(screen.getByRole("option", { name: "VPN 路由" }));+ await userEvent.click(preview.getByRole("button", { name: "Save changes" }));+ expect(preview.getByRole("status")).toHaveTextContent("Saved");+ expect(preview.getByRole("button", { name: "Save changes" })).toBeDisabled();+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");+});++it("uses the real provider manager and saves a new provider entirely in preview state", async () => {+ const source = "webui/src/components/settings/models/ProviderSettings.tsx";+ window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });+ vi.stubGlobal("fetch", fetch);+ render(<Gallery />);+ await screen.findByRole("heading", { name: "ProvidersSettings · 管理提供商" });+ const preview = within(screen.getByRole("region", { name: "Component preview" }));+ await userEvent.click(preview.getByRole("button", { name: "Manage providers" }));+ let dialog = within(screen.getByRole("dialog", { name: "Manage providers" }));+ expect(dialog.getByRole("button", { name: "Anthropic", exact: true })).toBeVisible();+ expect(dialog.getByTestId("provider-logo-anthropic")).toBeVisible();+ expect(dialog.queryByRole("button", { name: "OpenAI", exact: true })).not.toBeInTheDocument();++ await userEvent.click(dialog.getByRole("button", { name: "Add provider", exact: true }));+ await userEvent.click(screen.getByRole("option", { name: "OpenAI", exact: true }));+ dialog = within(screen.getByRole("dialog", { name: "OpenAI" }));+ await userEvent.type(dialog.getByLabelText("API key", { selector: "input" }), "gallery-example-key");+ const apiURL = dialog.getByLabelText("API URL");+ await userEvent.clear(apiURL);+ await userEvent.type(apiURL, "https://preview.example/v1");+ await userEvent.click(dialog.getByRole("button", { name: "Add provider", exact: true }));++ dialog = within(await screen.findByRole("dialog", { name: "Manage providers" }));+ await userEvent.click(dialog.getByRole("button", { name: "OpenAI", exact: true }));+ expect(screen.getByLabelText("API URL")).toHaveValue("https://preview.example/v1");+ await userEvent.keyboard("{Escape}{Escape}");+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(preview.getByRole("button", { name: "Manage providers" })).toHaveFocus();+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");+});++it("renders a registered channel's real secret fields and enable action without a gateway", async () => {+ const source = "nanobot/channels/telegram/webui/index.ts";+ window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });+ vi.stubGlobal("fetch", fetch);+ render(<Gallery />);+ await screen.findByRole("heading", { name: "Telegram · 频道配置" });+ const preview = within(screen.getByRole("region", { name: "Component preview" }));+ const token = preview.getByLabelText("Bot token", { selector: "input" });+ expect(token).toHaveAttribute("type", "password");+ await userEvent.click(preview.getByRole("switch", { name: "Enable channel", exact: true }));+ expect(token).toHaveAttribute("aria-invalid", "true");+ expect(preview.getByRole("switch", { name: "Enable channel", exact: true })).not.toBeChecked();+ await userEvent.type(token, "gallery-example-token");+ await userEvent.click(preview.getByRole("switch", { name: "Enable channel", exact: true }));+ expect(preview.getByRole("switch", { name: "Enable channel", exact: true })).toBeChecked();+ await userEvent.click(preview.getByRole("button", { name: "Advanced", exact: true }));+ expect(preview.getByRole("group", { name: "Connection mode" })).toBeVisible();+ expect(preview.getByRole("radio", { name: "Long polling" })).toBeChecked();+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(fetch.mock.calls[0][0]).toBe("/__nanobot_components");+});diff --git a/webui/src/tests/settings-overview.test.tsx b/webui/src/tests/settings-overview.test.tsxindex e24ab5446..9daa91038 100644--- a/webui/src/tests/settings-overview.test.tsx+++ b/webui/src/tests/settings-overview.test.tsx@@ -1,10 +1,12 @@import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";import { expect, it, vi } from "vitest";import { HostNavigationContext } from "@/components/remote/HostSwitcher";-import { AboutSettings } from "@/components/settings/overview/OverviewSettings";+import { AboutSettings, AppearanceSettings } from "@/components/settings/overview/OverviewSettings";+import { VersionCheckRowView } from "@/components/settings/overview/VersionCheckRowView";import { NanobotClient } from "@/lib/nanobot-client";import { ClientProvider } from "@/providers/ClientProvider";import type { SettingsPayload } from "@/lib/types";+import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTestHooks } from "@/tests/settings-test-utils";const thirdPartyBrandNotice =@@ -13,6 +15,31 @@ import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewTdescribe("Settings overview and appearance", () => {installSettingsViewTestHooks();+ it("displays a caller-owned version result and delegates checking without a client provider", () => {+ const check = vi.fn();+ render(<VersionCheckRowView currentVersion="0.3.5" checking={false}+ result={{ type: "update", latestVersion: "0.3.6", pypiUrl: "https://pypi.org/project/nanobot-ai/" }} onCheck={check} />);+ expect(screen.getByText("Update available v0.3.6")).toBeVisible();+ expect(screen.getByRole("link", { name: "PyPI" })).toHaveAttribute("href", "https://pypi.org/project/nanobot-ai/");+ fireEvent.click(screen.getByRole("button", { name: "Check for updates" }));+ expect(check).toHaveBeenCalledTimes(1);+ });++ it.each(["granted", "denied"])("updates task notifications only after browser permission is %s", async (permission) => {+ const requestPermission = vi.fn().mockResolvedValue(permission);+ vi.stubGlobal("Notification", { permission: "default", requestPermission });+ const changePreferences = vi.fn();+ render(<AppearanceSettings theme="light" onToggleTheme={vi.fn()} localPrefs={DEFAULT_LOCAL_PREFS} onChangeLocalPrefs={changePreferences} />);+ fireEvent.click(screen.getByRole("switch", { name: "Task notifications" }));+ expect(changePreferences).not.toHaveBeenCalled();+ await waitFor(() => expect(requestPermission).toHaveBeenCalledTimes(1));+ await act(async () => { await Promise.resolve(); });+ if (permission === "granted") {+ expect(changePreferences).toHaveBeenCalledTimes(1);+ expect(changePreferences.mock.calls[0][0](DEFAULT_LOCAL_PREFS).browserNotifications).toBe(true);+ } else expect(changePreferences).not.toHaveBeenCalled();+ });+it("links the host's short commit beside its version", () => {const commit = "abcdef12".repeat(5);diff --git a/webui/src/tests/star-prompt.test.tsx b/webui/src/tests/star-prompt.test.tsxindex 0a3a4fc60..d44f0519d 100644--- a/webui/src/tests/star-prompt.test.tsx+++ b/webui/src/tests/star-prompt.test.tsx@@ -5,6 +5,7 @@ import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, expect, it, vi } from "vitest";import { StarLink, StarPrompt } from "@/components/StarPrompt";+import { StarPromptView } from "@/components/StarPromptView";import { starPromptAction } from "@/lib/api";import i18n from "@/i18n";import { supportedLocales } from "@/i18n/config";@@ -34,6 +35,18 @@ async function clickStarLink(link: HTMLElement) {await act(async () => fireEvent.click(link));}+it("renders an invitation from caller-owned state and delegates actions without claiming it", async () => {+ const star = vi.fn();+ const dismiss = vi.fn();+ render(<StarPromptView open saving={false} error={false} onOpenChange={vi.fn()}+ onStar={star} onDismissForever={dismiss} />);+ await clickStarLink(screen.getByRole("link", { name: "Star on GitHub" }));+ expect(star).toHaveBeenCalledTimes(1);+ await userEvent.click(screen.getByRole("button", { name: "Don't ask again" }));+ expect(dismiss).toHaveBeenCalledTimes(1);+ expect(action).not.toHaveBeenCalled();+});+it("claims once on entry and lets users skip without permanently dismissing", async () => {const view = render(<StarPrompt ready />);await enter();diff --git a/webui/src/tests/toggle-button.test.tsx b/webui/src/tests/toggle-button.test.tsxindex df15100ea..ad74eecd3 100644--- a/webui/src/tests/toggle-button.test.tsx+++ b/webui/src/tests/toggle-button.test.tsx@@ -2,7 +2,7 @@ import { fireEvent, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";-import { ToggleButton } from "@/components/settings/ToggleButton";+import { ToggleButton } from "@/components/ui/toggle-button";describe("ToggleButton", () => {it("uses shared theme colors and compact dimensions in both states", () => {diff --git a/webui/src/tests/weixin-views.test.tsx b/webui/src/tests/weixin-views.test.tsxnew file mode 100644index 000000000..2fd32c597--- /dev/null+++ b/webui/src/tests/weixin-views.test.tsx@@ -0,0 +1,78 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import QRCode from "qrcode";++import type { NanobotFeatureInfo } from "@/lib/types";+import { WeixinConnectFlow } from "../../../nanobot/channels/weixin/webui/WeixinConnectFlow";+import { WeixinConnectFlowView } from "../../../nanobot/channels/weixin/webui/WeixinConnectFlowView";++const { requestMutation, useClientMock } = vi.hoisted(() => ({+ requestMutation: vi.fn(), useClientMock: vi.fn(),+}));+vi.mock("@/providers/ClientProvider", () => ({ useClient: useClientMock }));++const challenge = {+ session_id: "weixin-verification", status: "pending" as const,+ qr_url: "https://example.com/weixin", challenge: "verify_code" as const,+};+const feature: NanobotFeatureInfo = {+ name: "weixin", display_name: "WeChat", type: "channel", webui: "webui/index.tsx",+ enabled: false, configured: false, installed: true, ready: true, status: "not_enabled",+ install_supported: true, requires_restart: false,+};++beforeEach(() => {+ requestMutation.mockReset();+ useClientMock.mockReset().mockReturnValue({ client: { requestMutation } });+ vi.spyOn(QRCode, "toDataURL").mockResolvedValue("data:image/png;base64,preview");+});+afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });++describe("WeChat verification views", () => {+ it("renders without a runtime client and retains the verification draft after a rejected code", async () => {+ const onPoll = vi.fn().mockResolvedValue({ ...challenge, verification_failed: true });+ const props = {+ connect: challenge, busy: false, error: null, minimalPending: true,+ onStart: vi.fn(), onCancel: vi.fn(), onPoll,+ };+ const view = render(<WeixinConnectFlowView {...props} />);+ const code = screen.getByRole("textbox", { name: "Code" });+ fireEvent.change(code, { target: { value: " 987654 " } });+ fireEvent.click(screen.getByRole("button", { name: "Verify", exact: true }));+ await waitFor(() => expect(onPoll).toHaveBeenCalledWith({ verify_code: "987654" }));+ view.rerender(<WeixinConnectFlowView {...props} connect={{ ...challenge, verification_failed: true }} busy />);+ expect(code).toHaveValue(" 987654 ");+ expect(code).toHaveAttribute("aria-invalid", "true");+ expect(code).toHaveAttribute("aria-describedby", screen.getByRole("alert").id);+ expect(screen.getByRole("button", { name: "Verify", exact: true })).toBeDisabled();+ expect(useClientMock).not.toHaveBeenCalled();+ expect(requestMutation).not.toHaveBeenCalled();+ });++ it("pauses automatic polling for verification and submits the code through the real adapter", async () => {+ requestMutation.mockResolvedValueOnce(challenge);+ const onFeaturesUpdate = vi.fn();+ render(<WeixinConnectFlow token="tok" feature={feature} onFeaturesUpdate={onFeaturesUpdate} />);+ const code = await screen.findByRole("textbox", { name: "Code" });+ vi.useFakeTimers();+ await act(async () => { await vi.advanceTimersByTimeAsync(6000); });+ expect(requestMutation).toHaveBeenCalledTimes(1);+ expect(requestMutation).toHaveBeenCalledWith("settings.channel.connect.start", { channel: "weixin" }, 150_000);++ requestMutation.mockResolvedValueOnce({ ...challenge, verification_failed: true });+ fireEvent.change(code, { target: { value: "123456" } });+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Verify", exact: true })); });+ expect(requestMutation).toHaveBeenLastCalledWith("settings.channel.connect.poll", {+ channel: "weixin", session_id: "weixin-verification", verify_code: "123456",+ }, 150_000);+ expect(code).toHaveValue("123456");+ expect(code).toHaveAttribute("aria-invalid", "true");++ const features = { features: [{ ...feature, configured: true }], enabled_count: 0 };+ requestMutation.mockResolvedValueOnce({ ...challenge, status: "succeeded", nanobot_features: features });+ await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Verify", exact: true })); });+ expect(onFeaturesUpdate).toHaveBeenCalledWith(features);+ expect(screen.getByText("WeChat is connected.")).toBeVisible();+ expect(screen.queryByRole("textbox", { name: "Code" })).not.toBeInTheDocument();+ });+});diff --git a/webui/tailwind.config.js b/webui/tailwind.config.jsindex 12c29aa80..7fa0987b1 100644--- a/webui/tailwind.config.js+++ b/webui/tailwind.config.js@@ -8,6 +8,7 @@ export default {content: ["./index.html","./src/**/*.{ts,tsx}",+ ...(process.env.NODE_ENV === "production" ? ["!./src/dev/**"] : []),"../nanobot/channels/*/webui/**/*.{ts,tsx}","./node_modules/streamdown/dist/*.js",],diff --git a/webui/vite.config.ts b/webui/vite.config.tsindex af860645c..3655988dc 100644--- a/webui/vite.config.ts+++ b/webui/vite.config.ts@@ -3,6 +3,7 @@ import react from "@vitejs/plugin-react";import { readFileSync, writeFileSync } from "node:fs";import path from "node:path";import { gzipSync } from "node:zlib";+import { componentGallery } from "./src/dev/gallery/inventory-plugin";const GZIP_MIN_BYTES = 4 * 1024;const GZIP_ASSET_PATTERN = /\.(?:css|html|js|json|mjs|svg)$/i;@@ -119,7 +120,7 @@ export default defineConfig(({ mode }) => {const hmrPath = "/__nanobot_vite_hmr";return {- plugins: [react(), guardWebuiEntryChunk(), gzipWebuiAssets()],+ plugins: [react(), componentGallery(path.resolve(__dirname, "..")), guardWebuiEntryChunk(), gzipWebuiAssets()],resolve: {alias: {"@": path.resolve(__dirname, "./src"),@@ -176,7 +177,7 @@ export default defineConfig(({ mode }) => {coverage: {provider: "v8",include: ["src/**/*.{ts,tsx}"],- exclude: ["src/tests/**", "src/**/*.d.ts"],+ exclude: ["src/tests/**", "src/dev/**", "src/**/*.d.ts"],reporter: ["text", "json-summary"],thresholds: {statements: 85,