diff --git a/Dockerfile b/Dockerfile index 4b64e9692..4c411e410 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,6 +6,7 @@ WORKDIR /app/webui RUN npm ci COPY webui/ ./ COPY packages/client-events/ /app/packages/client-events/ +COPY nanobot/channels/ /app/nanobot/channels/ RUN mkdir -p /app/nanobot/web && npm run build FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim diff --git a/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx b/nanobot/channels/feishu/webui/FeishuAssistantsPanel.tsx index 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 ( - 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 : ( - - ), - footer: instances.some((instance) => instance.configured) ? ( - 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 } + />} + />; } diff --git a/nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsx b/nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsx new file mode 100644 index 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 & { + 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 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 : ( + {renderConnectFlow({ + instanceId: instance.id, + mode: "replace", + idleLabel: t("settings.channels.connect", { defaultValue: "Connect" }), + })} + ), + footer: instances.some((instance) => instance.configured) ? ( + instance.id).join(",")}>{renderConnectFlow({ + mode: "create", + idleLabel: tx("custom.addAssistant", "Add another assistant"), + })} + ) : 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.tsx index 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 ( } /> ); } diff --git a/nanobot/channels/feishu/webui/FeishuConnectFlowView.tsx b/nanobot/channels/feishu/webui/FeishuConnectFlowView.tsx new file mode 100644 index 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; + +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 ; +} diff --git a/nanobot/channels/linear/webui/LinearConnectFlow.tsx b/nanobot/channels/linear/webui/LinearConnectFlow.tsx index 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(null); - const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => { - if (!link) return; - flowRef.current?.scrollIntoView({ block: "nearest" }); - link.focus({ preventScroll: true }); - }, []); - - return ( -
- ( -
-
- - {tx("custom.waiting", "Waiting for Linear authorization...")} -
- {connect.qr_url ? ( - - ) : null} -
- )} - /> -
- ); + return } />; } diff --git a/nanobot/channels/linear/webui/LinearConnectFlowView.tsx b/nanobot/channels/linear/webui/LinearConnectFlowView.tsx new file mode 100644 index 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): 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(null); + const revealAuthorization = useCallback((link: HTMLAnchorElement | null) => { + if (!link) return; + flowRef.current?.scrollIntoView({ block: "nearest" }); + link.focus({ preventScroll: true }); + }, []); + + return ( +
+ ( +
+
+ + {tx("custom.waiting", "Waiting for Linear authorization...")} +
+ {connect.qr_url ? ( + + ) : null} +
+ )} + /> +
+ ); +} diff --git a/nanobot/channels/linear/webui/LinearMemberAccess.tsx b/nanobot/channels/linear/webui/LinearMemberAccess.tsx index 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 = "", disabled disabled?: 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(); - const duplicateNames = new Set(); - for (const member of members) { - if (names.has(member.name)) duplicateNames.add(member.name); - names.add(member.name); - } - - return ( -
- - - {payload && loading ? tx("members.refreshing", "Checking for updates…") : null} - - - {payload?.legacy_allow_all ?

- {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.")} -

: null} -
-
- - 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]")} /> -
- - - - - {tx("members.details", "About member access")} - - -
- {error ?

- {error} {tx("members.retry", "Refresh members to check the current state and try again.")} -

: null} - {payload && !error && visible.length === 0 ?

- {tx("members.empty", "No matching active members.")} -

: null} - -
    - {visible.map((member) => { - const save = saves[member.id]; - const statusId = `${panelId}-${member.id}-status`; - return
  • - - -
    -

    {member.name}

    -
    - - {save?.status === "saving" ? tx("members.working", "Saving…") : null} - {save?.status === "saved" ? <>{tx("members.saved", "Saved")} : null} - -
    - {duplicateNames.has(member.name) ? -

    {member.id}

    : null} -
    - }> - void store.setAllowed(member.id, allowed, - tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."))} /> -
    - {save?.status === "error" ? : null} -
  • ; - })} -
-
-
-
- ); + const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot); + return ; } diff --git a/nanobot/channels/linear/webui/LinearMemberAccessView.tsx b/nanobot/channels/linear/webui/LinearMemberAccessView.tsx new file mode 100644 index 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; +} + +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(); + const duplicateNames = new Set(); + for (const member of members) { + if (names.has(member.name)) duplicateNames.add(member.name); + names.add(member.name); + } + + return ( +
+ + + {payload && loading ? tx("members.refreshing", "Checking for updates…") : null} + + + {payload?.legacy_allow_all ?

+ {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.")} +

: null} +
+
+ + 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]")} /> +
+ + + + + {tx("members.details", "About member access")} + + +
+ {error ?

+ {error} {tx("members.retry", "Refresh members to check the current state and try again.")} +

: null} + {payload && !error && visible.length === 0 ?

+ {tx("members.empty", "No matching active members.")} +

: null} + +
    + {visible.map((member) => { + const save = saves[member.id]; + const statusId = `${panelId}-${member.id}-status`; + return
  • + + +
    +

    {member.name}

    +
    + + {save?.status === "saving" ? tx("members.working", "Saving…") : null} + {save?.status === "saved" ? <>{tx("members.saved", "Saved")} : null} + +
    + {duplicateNames.has(member.name) ? +

    {member.id}

    : null} +
    + }> + onSetAllowed(member.id, allowed, + tx("members.saveUnconfirmed", "Access was not confirmed. Refresh members before trying again."))} /> +
    + {save?.status === "error" ? : null} +
  • ; + })} +
+
+
+
+ ); +} diff --git a/nanobot/channels/linear/webui/LinearPanel.tsx b/nanobot/channels/linear/webui/LinearPanel.tsx index 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>(() => new Set()); const [visibleSecrets, setVisibleSecrets] = useState>({}); const [clearedSecrets, setClearedSecrets] = useState>(() => 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(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(null); - const [disconnectConfirmId, setDisconnectConfirmId] = useState(null); const [workspaceNotice, setWorkspaceNotice] = useState(null); const [workspaceError, setWorkspaceError] = useState(null); - const workspaceActionRef = useRef(null); - const skipMenuRestoreFocus = useRef(false); - const disconnectTarget = installations.find(item => item.organization_id === disconnectConfirmId); const savePromiseRef = useRef | null>(null); const secretSavePromiseRef = useRef | 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 ( - - ); + return setWorkspaceError(null)} + onRequestConnection={() => setConnectRequestId(id => id + 1)} onConfigureMcp={onConfigureMcp} + renderMemberAccess={(organizationId, disabled) => } + renderResetConnection={({ disabled, onComplete }) => { + setConnectRequestId(0); + setConnectionGeneration(value => value + 1); + setWorkspaceNotice(null); + setWorkspaceError(null); + onComplete(); + }} />} + renderConnectFlow={(renderActions) => 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.tsx new file mode 100644 index 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; + 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, "fields">; + state: LinearPanelState; + workspaces: LinearPanelWorkspaces; + onSave: () => Promise; + onSaveSecret: (key: string, value: string) => Promise; + onRefreshWorkspaces: (force?: boolean) => Promise; + onDisconnectWorkspace: (installation: LinearInstallationSummary, onRemoved: () => void) => Promise; + 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(null); + const workspaceActionRef = useRef(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(); + 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 ( + + ); +} diff --git a/nanobot/channels/linear/webui/LinearResetConnection.tsx b/nanobot/channels/linear/webui/LinearResetConnection.tsx index 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(null); - const inFlight = useRef(false); - const triggerRef = useRef(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 { - if (inFlight.current) return; - setOpen(value); - setError(null); - }}> -
- -
- { 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(); - }}> - - {tx("custom.resetTitle", "Reset Linear?")} - -
-

{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}

-
-
{tx("custom.resetClears", "Clears")}
-
{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}
-
{tx("custom.resetKeeps", "Keeps")}
-
{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}
-
-
-
-
- {error ?
-

{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}

-

{error}

-
: null} - - {t("settings.actions.cancel", { defaultValue: "Cancel" })} - - -
-
; + return ; } diff --git a/nanobot/channels/linear/webui/LinearResetConnectionView.tsx b/nanobot/channels/linear/webui/LinearResetConnectionView.tsx new file mode 100644 index 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; +}) { + const { t } = useTranslation(); + const tx = channelTranslator(t, "linear"); + const [open, setOpen] = useState(false); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const inFlight = useRef(false); + const triggerRef = useRef(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 { + if (inFlight.current) return; + setOpen(value); + setError(null); + }}> +
+ +
+ { 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(); + }}> + + {tx("custom.resetTitle", "Reset Linear?")} + +
+

{tx("custom.resetDescription", "Disconnect all workspaces linked through this app and stop the channel.")}

+
+
{tx("custom.resetClears", "Clears")}
+
{tx("custom.resetClearsDetail", "Member access settings and this instance’s app configuration, including saved credentials.")}
+
{tx("custom.resetKeeps", "Keeps")}
+
{tx("custom.resetKeepsDetail", "Linear app, issues, comments, chat history and pairing approvals.")}
+
+
+
+
+ {error ?
+

{tx("custom.resetIncomplete", "Reset is incomplete. Workspaces already removed stay removed; retry to finish the remaining steps.")}

+

{error}

+
: null} + + {t("settings.actions.cancel", { defaultValue: "Cancel" })} + + +
+
; +} diff --git a/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx b/nanobot/channels/weixin/webui/WeixinConnectFlow.tsx index 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 ( -
{ - event.preventDefault(); - const code = verificationCode.trim(); - if (!code) return; - void poll({ verify_code: code }).then((payload) => { - if (payload && !isVerificationChallenge(payload)) { - setVerificationCode(""); - } - }); - }} - > -
- {tx("custom.verifyTitle", "Verification required")} -
-

- {weixinConnectMessage(connect, tx)} -

-
- 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} - /> - -
-
- ); - }; - return ( 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) => } /> ); } diff --git a/nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx b/nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx new file mode 100644 index 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[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 ( +
{ + event.preventDefault(); + const code = verificationCode.trim(); + if (!code) return; + void poll({ verify_code: code }).then((payload) => { + if (payload && !isVerificationChallenge(payload)) { + setVerificationCode(""); + } + }); + }} + > +
+ {tx("custom.verifyTitle", "Verification required")} +
+

+ {weixinConnectMessage(connect, tx)} +

+
+ 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} + /> + +
+
+ ); + }; + + return weixinConnectMessage(payload, tx)} + />; +} diff --git a/nanobot/channels/weixin/webui/WeixinPanel.tsx b/nanobot/channels/weixin/webui/WeixinPanel.tsx index 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>({}); - const [advancedOpen, setAdvancedOpen] = useState(false); - const advancedPanelId = useId(); const [touchedFields, setTouchedFields] = useState>(() => 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 ( - + } + 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([ - ...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 } - | 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.tsx new file mode 100644 index 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; + configuredFields: Set; + 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>({}); + const [advancedOpen, setAdvancedOpen] = useState(false); + const advancedPanelId = useId(); + useEffect(() => setVisibleSecrets({}), [secretVisibilityKey]); + + return ( + + ); +} diff --git a/nanobot/channels/weixin/webui/presentation.ts b/nanobot/channels/weixin/webui/presentation.ts index 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([ + ...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 } + | 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.tsx index 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 ( } onFeaturesUpdate={onFeaturesUpdate} /> ); diff --git a/nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsx b/nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsx new file mode 100644 index 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; + +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 ; +} diff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.md new file mode 100644 index 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//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"; + + +``` + +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.md index 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. + ```text webui/ source tree (this directory) nanobot/web/dist/ build output served by the gateway diff --git a/webui/bun.lock b/webui/bun.lock index 81a57d874..7f4af13f1 100644 --- a/webui/bun.lock +++ b/webui/bun.lock @@ -539,7 +539,7 @@ "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], - "baseline-browser-mapping": ["baseline-browser-mapping@2.10.19", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.11.28", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-br0LOmjJqr6Rt4AEkadbcNf67Zpo7EPwKsWbjnRrJIa1QYFHQBqM4C7F2WTbV8ahTEcg1Eo+Y0aWjjORInYFyA=="], "binary-extensions": ["binary-extensions@2.3.0", "", {}, "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw=="], @@ -555,7 +555,7 @@ "camelcase-css": ["camelcase-css@2.0.1", "", {}, "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA=="], - "caniuse-lite": ["caniuse-lite@1.0.30001788", "", {}, "sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ=="], + "caniuse-lite": ["caniuse-lite@1.0.30001815", "", {}, "sha512-uDybUEyfgbyJJ93J1vikTylBX31AkdVYeVPeffMQpf8XN7hSfr0oZOn4VFOIMNvtU5+rHvC5Udg2TgtJKHm23Q=="], "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], diff --git a/webui/gallery.html b/webui/gallery.html new file mode 100644 index 000000000..2f3f0b2f7 --- /dev/null +++ b/webui/gallery.html @@ -0,0 +1,13 @@ + + + + + + Nanobot component gallery + + + +
+ + + diff --git a/webui/package-lock.json b/webui/package-lock.json index 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.json index 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.tsx index 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 = { @@ -24,12 +22,8 @@ const COPY: Record = { }, }; -export function ConnectionBadge() { +export function ConnectionBadge({ status }: { status: ConnectionStatus }) { const { t } = useTranslation(); - const { client } = useClient(); - const [status, setStatus] = useState(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.tsx index 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(() => initialPreview + const [state, setState] = useState(() => 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 ( -
-
- {state.status === "loading" ? ( -
- {t("filePreview.loading", { defaultValue: "Loading preview..." })} -
- {fileKindForPath(path) === "image" ?
- : <>{["w-2/3", "w-full", "w-5/6", "w-3/4"].map((width) => -
)}} -
-
- ) : state.status === "error" ? ( -
-
- -

{errorMessage}

-
-
- ) : state.payload.kind === "image" ? ( -
- - {}} onOpenChange={setImageOpen} /> -
- ) : ( -
- {state.payload.truncated ? ( -
- {t("filePreview.truncated", { - defaultValue: "Preview is truncated because this file is large.", - })} -
- ) : null} - -
- )} -
-
- ); + const reportImageError = useCallback(() => setState({ status: "error" }), []); + return ; } diff --git a/webui/src/components/FilePreviewPanelView.tsx b/webui/src/components/FilePreviewPanelView.tsx new file mode 100644 index 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 ( +
+
+ {state.status === "loading" ? ( +
+ {t("filePreview.loading", { defaultValue: "Loading preview..." })} +
+ {fileKindForPath(path) === "image" ?
+ : <>{["w-2/3", "w-full", "w-5/6", "w-3/4"].map((width) => +
)}} +
+
+ ) : state.status === "error" ? ( +
+
+ +

{errorMessage}

+
+
+ ) : state.payload.kind === "image" ? ( +
+ + {}} onOpenChange={onImageOpenChange} /> +
+ ) : ( +
+ {state.payload.truncated ? ( +
+ {t("filePreview.truncated", { + defaultValue: "Preview is truncated because this file is large.", + })} +
+ ) : null} + +
+ )} +
+
+ ); +} diff --git a/webui/src/components/StarPrompt.tsx b/webui/src/components/StarPrompt.tsx index 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 = ( - { if (event.button === 1) dismiss(); }}> - {!fullWidth && } - - {t(fullWidth ? "starPrompt.action" : "starPrompt.footerAction")} - - {fullWidth ? ( - - ) : } - - ); - return ( - <> - {fullWidth ? : link} - {error &&

{t("starPrompt.saveError")}

} - - ); + return ; } 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(null); - const titleRef = useRef(null); + const [starError, setStarError] = useState(false); useEffect(() => { const cancel = () => { interacted.current = true; }; @@ -101,47 +68,14 @@ export function StarPrompt({ ready }: { ready: boolean }) { } }; - return ( - - { - event.preventDefault(); - titleRef.current?.focus({ preventScroll: true }); - }} onCloseAutoFocus={(event) => { - event.preventDefault(); - previousFocus.current?.focus({ preventScroll: true }); - }}> - - - - - - -
- - {t("starPrompt.title")} - - - {t("starPrompt.intro")}{" "} - {t("starPrompt.invitation")}{" "} - {t("starPrompt.thanks")} - -
-
- -
- setOpen(false)} /> -
-
- - {error &&

{t("starPrompt.saveError")}

} -
-
- ); + const openRepository = () => { + setStarError(false); + void starPromptAction(client, "dismiss").then(() => setOpen(false)).catch(() => setStarError(true)); + }; + return 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.tsx new file mode 100644 index 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 = ( + { if (event.button === 1) onActivate(); }}> + {!fullWidth && } + + {t(fullWidth ? "starPrompt.action" : "starPrompt.footerAction")} + + {fullWidth ? ( + + ) : } + + ); + return ( + <> + {fullWidth ? : link} + {error &&

{t("starPrompt.saveError")}

} + + ); +} + +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(null); + return ( + + { + event.preventDefault(); + titleRef.current?.focus({ preventScroll: true }); + }} onCloseAutoFocus={onCloseAutoFocus}> + + + + + + +
+ + {t("starPrompt.title")} + + + {t("starPrompt.intro")}{" "} + {t("starPrompt.invitation")}{" "} + {t("starPrompt.thanks")} + +
+
+ +
+ +
+
+ + {error &&

{t("starPrompt.saveError")}

} +
+
+ ); +} diff --git a/webui/src/components/WebPreviewPanel.tsx b/webui/src/components/WebPreviewPanel.tsx index 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 ( -
-
-

{url?.href}

- - - -

{t("webPreview.isolated")}

-

{t("webPreview.blockedHint")}

- {url && isLoopbackHost(url.hostname) ?

{t("webPreview.loopback")}

: null} -
-
- {!restriction ? : null} - {url ? - - : null} -
- {restriction ?
- {t(`webPreview.${restriction}`)} -
: