diff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.md index 13a3424dd..5c260e513 100644 --- a/webui/COMPONENTS.md +++ b/webui/COMPONENTS.md @@ -13,13 +13,13 @@ Open `http://127.0.0.1:5173/gallery.html`. The gallery uses the existing Vite de 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. +Search by module name, exported name, path, or the example title in the selected language. 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. +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 language throughout the gallery, including navigation, usage notes, and preview controls. Language changes preserve the current preview and its drafts. Component names, API values, source examples, and simulated user content keep their original text. 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. @@ -83,6 +83,6 @@ The caller decides how to persist `enabled`; the switch implements the interacti 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. +Add examples to the appropriate feature file in `src/dev/gallery/`. Gallery translations live in `src/dev/gallery/locales/` under a development-only `gallery` namespace. Keep each locale's keys and interpolation variables aligned. Example `title`, `description`, and `options` fields are translation keys; `code` remains literal source. Use `useGalleryTranslation()` for preview interface copy and the product's existing translations for product controls. 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/browser/gallery-language.spec.ts b/webui/browser/gallery-language.spec.ts new file mode 100644 index 000000000..7212348fd --- /dev/null +++ b/webui/browser/gallery-language.spec.ts @@ -0,0 +1,118 @@ +import { expect, test } from "@playwright/test"; + +const locales = [ + { code: "en", label: "English", title: "Component gallery", search: "Search components", preview: "Component preview" }, + { code: "zh-CN", label: "简体中文", title: "组件图鉴", search: "搜索组件", preview: "组件预览" }, + { code: "zh-TW", label: "繁體中文", title: "元件圖鑑", search: "搜尋元件", preview: "元件預覽" }, + { code: "fr", label: "Français", title: "Galerie de composants", search: "Rechercher des composants", preview: "Aperçu du composant" }, + { code: "ja", label: "日本語", title: "コンポーネントギャラリー", search: "コンポーネントを検索", preview: "コンポーネントのプレビュー" }, + { code: "ko", label: "한국어", title: "컴포넌트 갤러리", search: "컴포넌트 검색", preview: "컴포넌트 미리보기" }, + { code: "es", label: "Español", title: "Galería de componentes", search: "Buscar componentes", preview: "Vista previa del componente" }, + { code: "pt-BR", label: "Português (Brasil)", title: "Galeria de componentes", search: "Buscar componentes", preview: "Prévia do componente" }, + { code: "vi", label: "Tiếng Việt", title: "Thư viện thành phần", search: "Tìm thành phần", preview: "Xem trước thành phần" }, + { code: "id", label: "Bahasa Indonesia", title: "Galeri komponen", search: "Cari komponen", preview: "Pratinjau komponen" }, +]; + +for (const locale of locales) { + test(`gallery switches to ${locale.code} without replacing preview state`, async ({ page }) => { + await page.setViewportSize({ width: locale.code === "en" || locale.code.startsWith("zh") ? 1280 : 390, height: 960 }); + let inventoryRequests = 0; + page.on("request", (request) => { if (new URL(request.url()).pathname === "/__nanobot_components") inventoryRequests += 1; }); + await page.goto("/gallery.html#component=webui%2Fsrc%2Fcomponents%2Fui%2Finput.tsx"); + const input = page.getByRole("region", { name: "Component preview", exact: true }).getByRole("textbox").first(); + await input.fill("Keep this draft 中文"); + const originalInput = await input.elementHandle(); + const code = await page.locator(".gallery-code").first().innerText(); + const originalHash = new URL(page.url()).hash; + + await page.locator(".gallery-header").getByRole("combobox").click(); + await page.getByRole("option", { name: locale.label, exact: true }).click(); + + await expect(page.getByRole("heading", { name: locale.title, exact: true })).toBeVisible(); + await expect(page.getByRole("searchbox", { name: locale.search })).toBeVisible(); + await expect(page.getByRole("region", { name: locale.preview, exact: true }).getByRole("textbox").first()).toHaveValue("Keep this draft 中文"); + expect(await originalInput!.evaluate((element) => element.isConnected)).toBe(true); + expect(new URL(page.url()).hash).toBe(originalHash); + await expect(page.locator(".gallery-code").first()).toHaveText(code); + expect(inventoryRequests).toBe(1); + await expect(page.locator("html")).toHaveAttribute("lang", locale.code); + expect(await page.evaluate(() => localStorage.getItem("nanobot.locale"))).toBe(locale.code); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + + await page.reload(); + await expect(page.getByRole("heading", { name: locale.title, exact: true })).toBeVisible(); + await expect(page.locator(".gallery-header").getByRole("combobox")).toHaveText(locale.label); + }); +} + +test("gallery localizes an existing error and retries in the selected language", async ({ page }) => { + await page.route("**/__nanobot_components", (route) => route.fulfill({ status: 503, body: "unavailable" })); + await page.goto("/gallery.html"); + await expect(page.getByRole("alert")).toContainText("Could not load the inventory"); + await page.locator(".gallery-header").getByRole("combobox").click(); + await page.getByRole("option", { name: "简体中文", exact: true }).click(); + await expect(page.getByRole("alert")).toContainText("无法加载组件目录"); + + await page.unroute("**/__nanobot_components"); + await page.getByRole("button", { name: "刷新目录" }).click(); + await expect(page.getByRole("region", { name: "组件预览", exact: true })).toBeVisible(); + await page.getByRole("button", { name: "全部源码", exact: true }).click(); + await page.getByRole("searchbox", { name: "搜索组件" }).fill("SettingsView"); + await page.locator('a[href="#component=webui%2Fsrc%2Fcomponents%2Fsettings%2FSettingsView.tsx"]').click(); + await expect(page.getByRole("heading", { name: "暂无独立预览", exact: true })).toBeVisible(); + await page.getByRole("button", { name: "预览", exact: true }).click(); + await expect(page.getByRole("region", { name: "组件预览", exact: true })).toBeVisible(); +}); + +test("gallery translates model labels and existing interaction feedback in a narrow dark view", async ({ page }) => { + await page.setViewportSize({ width: 390, height: 960 }); + await page.emulateMedia({ colorScheme: "dark" }); + await page.goto("/gallery.html#component=webui%2Fsrc%2Fcomponents%2Fsettings%2Fshared%2FModelControls.tsx"); + const preview = page.locator(".gallery-preview"); + await expect(preview.getByText("Provider", { exact: true })).toBeVisible(); + await expect(preview.getByText("Model", { exact: true })).toBeVisible(); + await page.locator(".gallery-header").getByRole("combobox").click(); + await page.getByRole("option", { name: "简体中文", exact: true }).click(); + await expect(preview.getByText("提供商", { exact: true })).toBeVisible(); + await expect(preview.getByText("模型", { exact: true })).toBeVisible(); + await expect(preview.getByText("推理强度", { exact: true })).toBeVisible(); + await expect(page.locator("html")).toHaveClass(/dark/); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true); + + await page.locator('a[href="#component=webui%2Fsrc%2Fcomponents%2Fui%2Fbutton.tsx"]').click(); + await preview.getByRole("button", { name: "destructive", exact: true }).click(); + await expect(preview.getByRole("status")).toHaveText("按钮点击次数:1"); + await page.locator(".gallery-header").getByRole("combobox").click(); + await page.getByRole("option", { name: "English", exact: true }).click(); + await expect(preview.getByRole("status")).toHaveText("Button clicks: 1"); +}); + +test("gallery preserves history states and subagent retries when changing language", async ({ page }) => { + await page.goto("/gallery.html#component=webui%2Fsrc%2Fcomponents%2Fthread%2FThreadHistoryStatus.tsx"); + const preview = page.locator(".gallery-preview"); + await expect(preview.getByRole("combobox", { name: "History state" })).toHaveText("loading"); + await preview.getByRole("combobox").click(); + await page.getByRole("option", { name: "exhausted", exact: true }).click(); + await expect(preview.getByText("No earlier messages", { exact: true })).toBeVisible(); + + await page.locator(".gallery-header").getByRole("combobox").click(); + await page.getByRole("option", { name: "简体中文", exact: true }).click(); + await expect(preview.getByRole("combobox", { name: "历史状态" })).toHaveText("exhausted"); + await expect(preview.getByText("没有更早的消息", { exact: true })).toBeVisible(); + await preview.getByRole("combobox").click(); + await page.getByRole("option", { name: "error", exact: true }).click(); + await preview.getByRole("button", { name: "加载失败,重试" }).click(); + await expect(preview.getByRole("combobox")).toHaveText("loading"); + await expect(preview.getByText("重试次数:1", { exact: true })).toBeVisible(); + + await page.locator('a[href="#component=webui%2Fsrc%2Fcomponents%2Fthread%2FSubagentThreadView.tsx"]').click(); + await preview.getByRole("combobox").click(); + await page.getByRole("option", { name: "error", exact: true }).click(); + await expect(preview.getByRole("button", { name: "加载失败,重试" })).toBeVisible(); + await page.locator(".gallery-header").getByRole("combobox").click(); + await page.getByRole("option", { name: "English", exact: true }).click(); + await expect(preview.getByRole("combobox")).toHaveText("error"); + await preview.getByRole("button", { name: "Loading failed. Retry" }).click(); + await expect(preview.getByRole("combobox")).toHaveText("ready"); + await expect(preview.getByText("Retries: 1", { exact: true })).toBeVisible(); +}); diff --git a/webui/browser/provider-parameters.spec.ts b/webui/browser/provider-parameters.spec.ts index e71619cfb..20f448707 100644 --- a/webui/browser/provider-parameters.spec.ts +++ b/webui/browser/provider-parameters.spec.ts @@ -6,7 +6,7 @@ for (const locale of ["en", "zh-CN"]) { await page.setViewportSize({ width, height: 900 }); await page.addInitScript((language) => localStorage.setItem("nanobot.locale", language), locale); await page.goto("/gallery.html#component=webui%2Fsrc%2Fcomponents%2Fsettings%2Fmodels%2FProviderParameterFields.tsx"); - const preview = page.getByRole("region", { name: "Component preview" }); + const preview = page.getByRole("region", { name: locale === "en" ? "Component preview" : "组件预览" }); const rows = preview.getByRole("button"); await expect(rows).toHaveCount(3); diff --git a/webui/src/dev/gallery/Gallery.tsx b/webui/src/dev/gallery/Gallery.tsx index e2d382fbe..b579a95f9 100644 --- a/webui/src/dev/gallery/Gallery.tsx +++ b/webui/src/dev/gallery/Gallery.tsx @@ -22,10 +22,15 @@ import { feishuWhatsAppChannelExamples } from "./channels-feishu-whatsapp"; import { linearChannelExamples } from "./channels-linear"; import { weixinChannelExamples } from "./channels-weixin"; import { foundationPath, type ComponentSource } from "./inventory"; +import { useGalleryTranslation } from "./i18n"; 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))); +const groupKeys: Record = { + All: "all", "Shared views & shell": "shared", Icons: "icons", Hosts: "hosts", Settings: "settings", + "Settings / shared": "settingsShared", Conversation: "conversation", Foundations: "foundations", Workbench: "workbench", +}; function selectedPath(): string { return new URLSearchParams(window.location.hash.slice(1)).get("component") ?? `${foundationPath}button.tsx`; @@ -33,8 +38,9 @@ function selectedPath(): string { export function Gallery() { const { theme, setTheme } = useTheme(); + const { t } = useGalleryTranslation(); const [inventory, setInventory] = useState([]); - const [error, setError] = useState(""); + const [error, setError] = useState(false); const [loading, setLoading] = useState(true); const [reload, setReload] = useState(0); const [query, setQuery] = useState(""); @@ -45,15 +51,15 @@ export function Gallery() { useEffect(() => { const controller = new AbortController(); setLoading(true); - setError(""); + setError(false); 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."); + if (!response.ok) throw new Error(`Inventory request failed: ${response.status}`); const data: ComponentSource[] = await response.json(); setInventory(data); }) - .catch((reason: unknown) => { - if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : String(reason)); + .catch(() => { + if (!controller.signal.aborted) setError(true); }) .finally(() => { if (!controller.signal.aborted) setLoading(false); }); return () => controller.abort(); @@ -69,12 +75,23 @@ export function Gallery() { return () => window.removeEventListener("hashchange", change); }, []); + useEffect(() => { document.title = t("ui.pageTitle"); }, [t]); + + const exampleTitle = (example: (typeof examples)[number]) => t(example.title, example.titleValues); + const groupLabel = (name: string): string => { + return name.startsWith("Channels / ") + ? t("ui.groups.channel", { channel: name.slice("Channels / ".length) }) + : t(`ui.groups.${groupKeys[name]}`); + }; 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 filtered = browsable.filter((item) => { + const example = examplesByPath.get(item.path); + return (group === "All" || item.group === group) + && `${item.path} ${item.exports.join(" ")} ${example ? exampleTitle(example) : ""}`.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) => @@ -85,19 +102,19 @@ export function Gallery() {
-

Component gallery · 组件图鉴

-

Try components and their states · 查看效果与交互状态

+

{t("ui.title")}

+

{t("ui.subtitle")}

- +
-
- {error ?
{error}
: null} + {error ?
{t("ui.inventoryFailure")}
: null} {current ?
-

{current.group}

-

{example?.title ?? current.name}

+

{groupLabel(current.group)}

+

{example ? exampleTitle(example) : current.name}

{current.path}

{example ? <> -

{example.description}

-
-

Usage · 使用方法

-

{example.options}

{example.code}
- {example.files.length > 1 ?

This example composes: {example.files.map((file) => file.split("/").pop()).join(", ")}

: null} +

{t(example.description)}

+
+

{t("ui.usage")}

+

{t(example.options)}

{example.code}
+ {example.files.length > 1 ?

{t("ui.composedModules", { modules: example.files.map((file) => file.split("/").pop()).join(", ") })}

: null}
:
-

Source only · 暂无独立预览

-

This entry indexes a source module. Use Previews to browse working examples. 此条目收录源码;切换到“预览”查看可操作示例。

+

{t("ui.sourceOnlyTitle")}

+

{t("ui.sourceOnlyDescription")}

{relatedExamples.length > 0 ?
-

Related component previews · 相关组件预览

+

{t("ui.relatedPreviews")}

: null}
} -

Exports · 导出

-

{current.exports.join(", ") || "Internal module"}

+

{t("ui.exports")}

+

{current.exports.join(", ") || t("ui.internalModule")}

-

Direct references · 使用位置

-

Imports and re-exports in product source; tests and this gallery are excluded. Plugin registration may also load modules indirectly.

+

{t("ui.references")}

+

{t("ui.referencesDescription")}

{current.usedBy.length ?
    {current.usedBy.map((file) =>
  • {file}
  • )}
- :

No direct source references found.

} + :

{t("ui.noReferences")}

}
-
Source code · 源码 +
{t("ui.sourceCode")}
{current.source}
-
: !error ?

{loading ? "Loading components…" : "No component source files found."}

: null} + : !error ?

{t(loading ? "ui.loadingComponents" : "ui.noComponentFiles")}

: null}
diff --git a/webui/src/dev/gallery/channels-feishu-whatsapp.tsx b/webui/src/dev/gallery/channels-feishu-whatsapp.tsx index 1c6425b0a..62622d773 100644 --- a/webui/src/dev/gallery/channels-feishu-whatsapp.tsx +++ b/webui/src/dev/gallery/channels-feishu-whatsapp.tsx @@ -6,6 +6,7 @@ import { WhatsAppConnectFlowView } from "../../../../nanobot/channels/whatsapp/w import type { ChannelConnectPayload, NanobotChannelInstanceInfo } from "@/lib/types"; import { channelFeatures } from "./channel-fixtures"; import { StatePicker, type ComponentExample } from "./example"; +import { useGalleryTranslation } from "./i18n"; const connectStates = ["idle", "starting", "pending", "succeeded", "expired", "failed", "cancelled", "error"] as const; type ConnectState = typeof connectStates[number]; @@ -20,18 +21,19 @@ function connectSnapshot(state: ConnectState): ChannelConnectPayload | null { } function ConnectPreview({ channel }: { channel: "feishu" | "whatsapp" }) { + const { t } = useGalleryTranslation(); const [state, setState] = useState("pending"); const connect = connectSnapshot(state); const props = { connect, busy: state === "starting", - error: state === "error" ? "Authorization is temporarily unavailable. Try again." : null, + error: state === "error" ? t("previews.channelConnect.error") : null, onStart: () => setState("pending"), onCancel: () => setState("cancelled"), onPoll: async () => connect, }; return <> - + {channel === "feishu" ? : } @@ -87,21 +89,22 @@ function AssistantAuthorizationPreview({ idleLabel }: FeishuConnectOptions) { } function FeishuAssistantsPreview() { + const { t } = useGalleryTranslation(); const [state, setState] = useState("mixed"); const [instances, setInstances] = useState(() => assistantSnapshots("mixed")); - const [action, setAction] = useState(""); + const [action, setAction] = useState<{ kind: "on" | "off"; name: string } | { kind: "saved"; name: string; amount: number } | null>(null); 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, + runtime_error: state === "failed" ? t("previews.feishuAssistants.error") : undefined, }; return <> - { + { setState(next); setInstances(assistantSnapshots(next)); - setAction(""); + setAction(null); }} /> current.map((item) => item.id === instance.id ? { ...item, enabled, runtime_status: enabled ? "running" : "stopped", } : item)); - setAction(`${instance.display_name}: ${enabled ? "On" : "Off"}`); + setAction({ kind: enabled ? "on" : "off", name: instance.display_name?.trim() || instance.name.trim() || instance.id }); }} 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`); + setAction({ kind: "saved", name: instance.display_name?.trim() || instance.name.trim() || instance.id, amount: Object.keys(values).length }); }} renderConnectFlow={(options) => } /> - {action ?

{action}

: null} + {action ?

{t(`previews.feishuAssistants.${action.kind}`, { name: action.name, amount: action.kind === "saved" ? action.amount : undefined })}

: null} ; } export const feishuWhatsAppChannelExamples: ComponentExample[] = [ { - title: "FeishuConnectFlowView · 飞书扫码授权", + title: "previews.feishuConnect.title", files: ["nanobot/channels/feishu/webui/FeishuConnectFlowView.tsx", "webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx"], - description: "查看飞书真实扫码界面,切换等待、授权成功、到期、取消与错误,体验取消和重新扫码。", - options: "connect、busy 和 error 是已有显示状态;视图本地生成二维码。开始、取消与轮询由功能入口提供,预览回调只改变当前示例。", + description: "previews.feishuConnect.description", + options: "previews.feishuConnect.options", code: "", Preview: FeishuConnectionPreview, }, { - title: "FeishuAssistantsPanelView · 飞书助手管理", + title: "previews.feishuAssistants.title", files: ["nanobot/channels/feishu/webui/FeishuAssistantsPanelView.tsx", "webui/src/components/settings/channels/ChannelInstancesPanelView.tsx"], - description: "展示多个真实助手卡片、运行与授权状态,试用开关、高级设置、保存和添加另一个助手。", - options: "feature 和 instances 提供助手快照;视图管理字段草稿与保存反馈。onToggleInstance、onSaveInstance 与 renderConnectFlow 由所属功能接入运行时操作。", + description: "previews.feishuAssistants.description", + options: "previews.feishuAssistants.options", code: "", Preview: FeishuAssistantsPreview, }, { - title: "WhatsAppConnectFlowView · WhatsApp 设备关联", + title: "previews.whatsappConnect.title", files: ["nanobot/channels/whatsapp/webui/WhatsAppConnectFlowView.tsx"], - description: "使用正式 WhatsApp 极简二维码布局,比较自动连接、关联成功、到期和错误提示,并试用关联另一个账号。", - options: "此视图沿用自动开始和极简布局的显示规则;调用方控制状态和重试。真实自动开始、强制重试和轮询仍由连接功能入口负责。", + description: "previews.whatsappConnect.description", + options: "previews.whatsappConnect.options", code: "", Preview: WhatsAppConnectionPreview, }, diff --git a/webui/src/dev/gallery/channels-linear.tsx b/webui/src/dev/gallery/channels-linear.tsx index d73d98252..84648aa39 100644 --- a/webui/src/dev/gallery/channels-linear.tsx +++ b/webui/src/dev/gallery/channels-linear.tsx @@ -12,6 +12,7 @@ import { LinearResetConnectionView } from "../../../../nanobot/channels/linear/w import type { LinearInstallationSummary } from "../../../../nanobot/channels/linear/webui/types"; import { channelFeatures } from "./channel-fixtures"; import { StatePicker, type ComponentExample } from "./example"; +import { useGalleryTranslation } from "./i18n"; const workspace: LinearInstallationSummary = { organization_id: "gallery-workspace", organization_name: "Nanobot team", @@ -32,15 +33,18 @@ function memberSnapshot(story: MemberStory): LinearMemberAccessSnapshot { legacy_allow_all: story === "allow-all", members: story === "empty" ? [] : members, }, loading: story === "loading" || story === "refreshing", - error: story === "error" ? "Member directory is unavailable." : null, + error: story === "error" ? "previews.linearMembers.loadError" : null, saves: story === "saving" ? { "gallery-alex": { status: "saving" } } - : story === "save-error" ? { "gallery-alex": { status: "error", message: "Access was not confirmed." } } : {}, + : story === "save-error" ? { "gallery-alex": { status: "error", message: "previews.linearMembers.saveError" } } : {}, }; } function MemberList({ story = "members", disabled = false }: { story?: MemberStory; disabled?: boolean }) { + const { t } = useGalleryTranslation(); const [snapshot, setSnapshot] = useState(() => memberSnapshot(story)); - return [id, save.status === "error" ? { ...save, message: t(save.message) } : save])), + }} disabled={disabled} onLoad={(force) => { if (force) setSnapshot(memberSnapshot("members")); }} onSetAllowed={(id, allowed) => setSnapshot(current => ({ ...current, payload: current.payload ? { ...current.payload, @@ -51,8 +55,9 @@ function MemberList({ story = "members", disabled = false }: { story?: MemberSto } function MembersPreview() { + const { t } = useGalleryTranslation(); const [story, setStory] = useState("members"); - return <>
; @@ -68,33 +73,36 @@ function connection(story: ConnectStory): ChannelConnectPayload | null { function AuthorizationPreview() { const { t } = useTranslation(); + const { t: g } = useGalleryTranslation(); const [story, setStory] = useState("idle"); const connect = connection(story); - return <> - setStory("pending")} onCancel={() => setStory("cancelled")} onPoll={async () => connect} /> -

授权链接与工作区为示例数据;开始、取消只更新预览阶段。

; +

{g("previews.linearConnect.hint")}

; } type ResetStory = "success" | "partial-error"; function ResetAction({ story = "success", disabled = false, onComplete }: { story?: ResetStory; disabled?: boolean; onComplete?: () => void; }) { - const [feedback, setFeedback] = useState(""); + const { t } = useGalleryTranslation(); + const [completed, setCompleted] = useState(false); return <> { 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("预览工作区及应用设置已清除。"); + if (story === "partial-error") throw new Error(t("previews.linearReset.error")); + setCompleted(true); onComplete?.(); - }} />

{feedback}

; + }} />

{completed ? t("previews.linearReset.completed") : ""}

; } function ResetPreview() { + const { t } = useGalleryTranslation(); const [story, setStory] = useState("success"); - return <> + return <> ; } @@ -104,7 +112,7 @@ function panelFeature(story: PanelStory): NanobotFeatureInfo { 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, + runtime_error: story === "runtime-error" ? "previews.linearPanel.runtimeError" : 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" }, }; @@ -112,6 +120,7 @@ function panelFeature(story: PanelStory): NanobotFeatureInfo { function PanelComposition({ story }: { story: PanelStory }) { const { t, i18n } = useTranslation(); + const { t: g } = useGalleryTranslation(); const [feature, setFeature] = useState(() => panelFeature(story)); const setup = channelSetup(feature, i18n.resolvedLanguage ?? i18n.language); const fields = setup.fields ?? []; @@ -121,41 +130,41 @@ function PanelComposition({ story }: { story: PanelStory }) { const [visibleSecrets, setVisibleSecrets] = useState>({}); const [dirty, setDirty] = useState(false); const [saved, setSaved] = useState(false); - const [notice, setNotice] = useState(story === "save-error" ? "Settings could not be saved. Your draft was kept." : null); + const [notice, setNotice] = useState(story === "save-error" ? "previews.linearPanel.saveError" : null); const [workspaceError, setWorkspaceError] = useState(null); const [loading, setLoading] = useState(story === "loading"); - const [inspectionError, setInspectionError] = useState(story === "inspection-error" ? "Connected workspaces could not be inspected." : null); + const [inspectionError, setInspectionError] = useState(story === "inspection-error" ? "previews.linearPanel.inspectionError" : null); const [installations, setInstallations] = useState(story === "connected" || story === "missing-scopes" ? [story === "missing-scopes" ? { ...workspace, authorization_status: "missing_scopes", missing_scopes: ["app:mentionable"] } : workspace] : []); const [connectStory, setConnectStory] = useState("idle"); - const [feedback, setFeedback] = useState(""); + const [feedback, setFeedback] = useState<{ key: string; name?: string } | null>(null); 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; } + if (story === "save-error") { setNotice("previews.linearPanel.saveError"); return false; } setFeature(current => ({ ...current, config_values: { ...current.config_values, ...values } })); setDirty(false); setSaved(true); setNotice(null); return true; }; const connect = connection(connectStory); - return <> 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 }} + state={{ busy: false, dirty, saving: false, saved, connecting, credentialsSaved, connectionGeneration: 0, notice: notice ? g(notice) : null }} workspaces={{ installations: loading || inspectionError ? null : installations, - logos: {}, loading, inspectionError, + logos: {}, loading, inspectionError: inspectionError ? g(inspectionError) : null, 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("已刷新示例工作区。"); }} + onRefreshWorkspaces={async () => { setLoading(false); setInspectionError(null); setFeedback({ key: "previews.linearPanel.refreshed" }); }} 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}`); + onRemoved(); setFeedback({ key: "previews.linearPanel.removed", name: item.organization_name }); }} onClearWorkspaceError={() => setWorkspaceError(null)} onRequestConnection={() => setConnectStory("pending")} - onConfigureMcp={() => setFeedback("已选择 Linear MCP 配置入口。")} + onConfigureMcp={() => setFeedback({ key: "previews.linearPanel.mcp" })} renderMemberAccess={(organizationId, disabled) => } renderResetConnection={({ disabled, onComplete }) => { setInstallations([]); setConfiguredFields(new Set()); setFeature(panelFeature("setup")); @@ -166,31 +175,32 @@ function PanelComposition({ story }: { story: PanelStory }) { suppressSucceeded={feature.runtime_status === "running" || feature.runtime_status === "failed"} renderActions={renderActions} onStart={() => setConnectStory("pending")} onCancel={() => setConnectStory("cancelled")} onPoll={async () => connect} />} /> -

{feedback}

; +

{feedback ? g(feedback.key, { name: feedback.name }) : ""}

; } function PanelPreview() { + const { t } = useGalleryTranslation(); const [story, setStory] = useState("connected"); - return <>; } export const linearChannelExamples: ComponentExample[] = [ - { title: "LinearPanelView · Linear 配置", files: ["nanobot/channels/linear/webui/LinearPanelView.tsx"], Preview: PanelPreview, - description: "真实 Linear 配置面板:应用信息、密钥、高级设置、工作区菜单、成员权限及浏览器授权。", - options: "state 与 workspaces 提供快照;工作区、保存与 MCP 操作由回调接入。三个插槽组合生产所用的成员、授权和重置视图。", + { title: "previews.linearPanel.title", files: ["nanobot/channels/linear/webui/LinearPanelView.tsx"], Preview: PanelPreview, + description: "previews.linearPanel.description", + options: "previews.linearPanel.options", code: "" }, - { title: "LinearMemberAccessView · 成员访问", files: ["nanobot/channels/linear/webui/LinearMemberAccessView.tsx"], Preview: MembersPreview, - description: "展开成员目录、搜索同名成员、修改权限;比较加载、刷新、空列表、保存和确认失败状态。", - options: "snapshot 是已确认的成员状态。onLoad 与 onSetAllowed 交给频道入口;权限校验仍由网关负责。", + { title: "previews.linearMembers.title", files: ["nanobot/channels/linear/webui/LinearMemberAccessView.tsx"], Preview: MembersPreview, + description: "previews.linearMembers.description", + options: "previews.linearMembers.options", code: "" }, - { title: "LinearConnectFlowView · Linear 授权", files: ["nanobot/channels/linear/webui/LinearConnectFlowView.tsx"], Preview: AuthorizationPreview, - description: "真实浏览器授权入口与等待提示,支持开始、取消、成功与失败阶段。", - options: "复用 ChannelQrConnectFlowView,Linear 提供浏览器授权展示、标签与焦点处理。会话创建及轮询留在运行时入口。", + { title: "previews.linearConnect.title", files: ["nanobot/channels/linear/webui/LinearConnectFlowView.tsx"], Preview: AuthorizationPreview, + description: "previews.linearConnect.description", + options: "previews.linearConnect.options", code: "" }, - { title: "LinearResetConnectionView · 重置连接", files: ["nanobot/channels/linear/webui/LinearResetConnectionView.tsx"], Preview: ResetPreview, - description: "打开重置确认,查看清除与保留范围、忙碌状态和部分完成后的重试提示。", - options: "onReset 负责运行完整撤销与清理事务;视图管理确认、错误、关闭限制与焦点恢复。", + { title: "previews.linearReset.title", files: ["nanobot/channels/linear/webui/LinearResetConnectionView.tsx"], Preview: ResetPreview, + description: "previews.linearReset.description", + options: "previews.linearReset.options", code: "" }, ]; diff --git a/webui/src/dev/gallery/channels-weixin.tsx b/webui/src/dev/gallery/channels-weixin.tsx index f4f7ac8c9..4b0927559 100644 --- a/webui/src/dev/gallery/channels-weixin.tsx +++ b/webui/src/dev/gallery/channels-weixin.tsx @@ -15,6 +15,7 @@ import { import { channelFeatures } from "./channel-fixtures"; import { StatePicker, type ComponentExample } from "./example"; +import { useGalleryTranslation } from "./i18n"; const scan: ChannelConnectPayload = { session_id: "gallery-weixin", @@ -26,6 +27,7 @@ type ConnectState = "starting" | "scan" | "verify" | "verify-error" | "connected | "expired" | "failed" | "cancelled" | "error"; function WeixinConnectPreview() { + const { t } = useGalleryTranslation(); const [mode, setMode] = useState("scan"); const [notice, setNotice] = useState(""); const connect: ChannelConnectPayload | WeixinVerificationPayload | null = mode === "starting" ? null @@ -35,12 +37,12 @@ function WeixinConnectPreview() { } : { ...scan, status: mode === "connected" ? "succeeded" : mode }; return <> - { setMode("scan"); setNotice("已显示新的预览二维码。"); }} + error={mode === "error" ? t("previews.weixinConnect.error") : null} + onStart={() => { setMode("scan"); setNotice("previews.weixinConnect.refreshed"); }} onCancel={() => setMode("cancelled")} onPoll={async (params) => { if (params?.verify_code === "123456") { @@ -50,7 +52,7 @@ function WeixinConnectPreview() { setMode("verify-error"); return { ...scan, challenge: "verify_code", verification_failed: true }; }} /> -

{notice || "验证码预览输入 123456 可完成连接;其他输入会保留草稿并显示错误。"}

+

{t(notice || "previews.weixinConnect.hint")}

; } @@ -58,6 +60,7 @@ type PanelState = "unconfigured" | "running" | "auth-expired" | "saving" | "save function WeixinPanelPreview() { const { t, i18n } = useTranslation(); + const { t: g } = useGalleryTranslation(); const channelTx = channelTranslator(t, "weixin"); const [mode, setMode] = useState("running"); const [edited, setEdited] = useState(false); @@ -80,14 +83,14 @@ function WeixinPanelPreview() { const runtimeError = mode === "auth-expired" ? channelTx("custom.expired", WEIXIN_AUTH_EXPIRED_MESSAGE) : undefined; return <> - { setMode(next); setEdited(false); }} /> ' }, - { title: "WeixinConnectFlowView · 微信扫码与验证", files: ["nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx"], - Preview: WeixinConnectPreview, description: "比较扫码、验证码、成功、过期、取消和连接错误。", - options: "视图接收连接快照与操作回调,并保留验证码草稿。二维码生成在浏览器中进行;授权启动、轮询暂停、刷新和取消由真实入口负责。", + { title: "previews.weixinConnect.title", files: ["nanobot/channels/weixin/webui/WeixinConnectFlowView.tsx"], + Preview: WeixinConnectPreview, description: "previews.weixinConnect.description", + options: "previews.weixinConnect.options", code: '' }, ]; diff --git a/webui/src/dev/gallery/channels.tsx b/webui/src/dev/gallery/channels.tsx index 9596668c0..751f4043c 100644 --- a/webui/src/dev/gallery/channels.tsx +++ b/webui/src/dev/gallery/channels.tsx @@ -10,11 +10,13 @@ import type { ChannelValidationPayload } from "@/lib/types"; import { copyTextToClipboard } from "@/lib/clipboard"; import { channelFeatures } from "./channel-fixtures"; import { StatePicker, type ComponentExample } from "./example"; +import { useGalleryTranslation } from "./i18n"; function ChannelEntryPreview({ name }: { name: string }) { const { t, i18n } = useTranslation(); + const { t: g } = useGalleryTranslation(); const [mode, setMode] = useState<"setup" | "configured" | "enabled" | "checking" | "error">("setup"); - return <> ; @@ -26,13 +28,14 @@ function ChannelFormPreview({ name, mode, locale, t }: { locale: string; t: ReturnType["t"]; }) { + const { t: g } = useGalleryTranslation(); 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 }; + runtime_error: mode === "error" ? g("previews.channel.credentialsError") : undefined }; const setup = channelSetup(feature, locale); const fields = setup.fields ?? []; const requirementKeys = new Set((setup.requirements ?? []).flatMap((item) => item.alternatives.flat())); @@ -54,27 +57,27 @@ function ChannelFormPreview({ name, mode, locale, t }: { const [clearedSecrets, setClearedSecrets] = useState>(() => new Set()); const [errors, setErrors] = useState>({}); const [advancedOpen, setAdvancedOpen] = useState(false); - const [notice, setNotice] = useState(null); + const [notice, setNotice] = useState<{ key: string } | { message: 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." })); + "settings.channels.fieldRequired"); 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." })); + setNotice({ key: "settings.channels.validationFailed" }); return false; } setSaved(true); - setNotice("预览配置已保存"); + setNotice({ key: "settings.channels.savedSettings" }); 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" }], + checks: [{ id: "preview", label: g("previews.channel.validation"), status: "pass" }], } : null; return ; } @@ -106,10 +111,11 @@ const genericRegistrations = registeredChannelUiContributions() .filter(({ contribution }) => !contribution.Panel && !contribution.ConnectFlow); export const channelExamples: ComponentExample[] = genericRegistrations.map(({ channel, webui, contribution }, index) => ({ - title: `${contribution.presentation.displayName} · 频道配置`, + title: "previews.channel.title", + titleValues: { channel: contribution.presentation.displayName }, files: [`nanobot/channels/${channel}/${webui}`, ...(index === 0 ? ["webui/src/components/settings/channels/ChannelSetupSurfaceView.tsx"] : [])], - description: "查看真实频道配置表单与状态。", - options: "使用频道注册定义、Python 设置契约快照和生产 ChannelSetupSurfaceView。输入、凭据显示、预设、检查与开关只更新当前预览。", + description: "previews.channel.description", + options: "previews.channel.options", code: ``, Preview: () => , })); diff --git a/webui/src/dev/gallery/content.tsx b/webui/src/dev/gallery/content.tsx index 2ea18002b..e402daa06 100644 --- a/webui/src/dev/gallery/content.tsx +++ b/webui/src/dev/gallery/content.tsx @@ -6,8 +6,10 @@ import { SessionInfoPopoverView } from "@/components/thread/SessionInfoPopoverVi import { SubagentThreadView } from "@/components/thread/SubagentThreadView"; import type { AutomationUpdatePayload, SessionAutomationJob, UIMessage } from "@/lib/types"; import { StatePicker, type ComponentExample } from "./example"; +import { useGalleryTranslation } from "./i18n"; function FilePreview() { + const { t } = useGalleryTranslation(); const [mode, setMode] = useState<"markdown" | "text" | "image" | "truncated" | "loading" | "error" | "route_missing">("markdown"); const [imageOpen, setImageOpen] = useState(false); const path = mode === "image" ? "nanobot.png" : mode === "markdown" || mode === "truncated" ? "REPORT.md" : "greeting.ts"; @@ -20,7 +22,7 @@ function FilePreview() { ? '# Skills 迁移报告\n\n已完成迁移,**原文件保持不变**。\n\n## 验证结果\n\n| 项目 | 结果 |\n| --- | --- |\n| 文件数量 | 1,199 个 |\n| 校验 | SHA-256 一致 |\n\n- [x] 保留原目录\n- [x] 检查引用\n\n## 下一步\n\n打开技能目录,确认所需服务已连接。\n\n```sh\nls skills/\n```\n\n![示意图](https://example.com/chart.png)\n' : 'export const greeting = "Hello, Nanobot";\n\nexport function greet(name: string) {\n return `${greeting}, ${name}`;\n}\n' } }; return
- { setMode(next); setImageOpen(false); }} />
("available"); const [revision, setRevision] = useState(0); const url = mode === "invalid" ? null : new URL(mode === "sameOrigin" ? window.location.href : "https://example.com/preview"); return
- +
setRevision((value) => value + 1)}> -