Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(channel): redesign the agent channel settings page (#21658)

Arvin Xu12eda1519611
diff --git a/locales/en-US/agent.json b/locales/en-US/agent.json
index 276e51b5b81..6512e1e9661 100644
--- a/locales/en-US/agent.json
+++ b/locales/en-US/agent.json
@@ -1,4 +1,33 @@
{
+ "channel.access.dm.approval": "Strangers need my approval",
+ "channel.access.dm.approvalDesc": "A stranger gets a pairing code, and you run /approve to let them in.",
+ "channel.access.dm.closed": "No direct messages",
+ "channel.access.dm.closedDesc": "It ignores DMs and points people to a shared group instead.",
+ "channel.access.dm.everyone": "Everyone",
+ "channel.access.dm.everyoneDesc": "Anyone can message it directly.",
+ "channel.access.dm.label": "Who can message it directly",
+ "channel.access.dm.listed": "Only people on the list",
+ "channel.access.dm.listedDesc": "Only listed people can use it; everyone else is turned away.",
+ "channel.access.group.allowlist": "Only chosen groups",
+ "channel.access.group.allowlistDesc": "Replies only in the groups you list below.",
+ "channel.access.group.disabled": "Not in groups",
+ "channel.access.group.disabledDesc": "It ignores group messages and points people to a DM.",
+ "channel.access.group.label": "How it responds in groups and channels",
+ "channel.access.group.listNote": "The people list above also applies here: only people on it can use the bot in groups.",
+ "channel.access.group.open": "Every group and channel",
+ "channel.access.group.openDesc": "Replies whenever it is @mentioned.",
+ "channel.access.identity.approverMissing": "To approve strangers, add your own ID first, or nobody can run /approve.",
+ "channel.access.identity.desc": "Lets the bot reach you with reminders and notices, and makes you the one who approves strangers. The settings below never block you.",
+ "channel.access.identity.required": "Required to approve strangers",
+ "channel.access.list.approved": "Approved people",
+ "channel.access.list.clearContent": "Switching to Everyone also removes the {{count}} people on the list, since a filled list limits everyone.",
+ "channel.access.list.clearOk": "Switch and clear",
+ "channel.access.list.clearTitle": "Clear the list?",
+ "channel.access.list.emptyApproval": "No one is approved yet. Strangers get a pairing code.",
+ "channel.access.list.emptyListed": "The list is empty, so apart from you nobody can message it yet.",
+ "channel.access.list.hint": "The list applies everywhere: only these people can use the bot, in DMs and in groups.",
+ "channel.access.list.listed": "People on the list",
+ "channel.access.recommended": "Recommended",
"channel.allowFrom": "Allowed Users",
"channel.allowFromAdd": "Add user",
"channel.allowFromEmpty": "No users added yet — anyone can interact with the bot.",
@@ -78,7 +107,6 @@
"channel.botWakeScopeNoneHint": "The bot never joins unprompted.",
"channel.botWakeWindowSeconds": "Follow-up window (seconds)",
"channel.botWakeWindowSecondsHint": "After the bot speaks, plain messages in the same place within this time count as a follow-up to it.",
- "channel.channelListLimit": "Lists hold at most {{max}} entries — remove one first.",
"channel.charLimit": "Character Limit",
"channel.charLimitHint": "Maximum number of characters per message",
"channel.comingSoon": "Coming Soon",
@@ -102,10 +130,10 @@
"channel.connectionError.application_not_found": "The bot application does not exist. Check the application ID in the platform console.",
"channel.connectionError.connection_closed": "The platform connection was interrupted. LobeHub will try to reconnect automatically.",
"channel.connectionError.invalid_credentials": "The bot credentials are invalid. Check the application ID, secret, and access tokens.",
- "channel.connectionError.missing_credentials": "Required bot credentials are missing. Complete the channel configuration and try again.",
+ "channel.connectionError.missing_credentials": "Required bot credentials are missing. Complete the bot configuration and try again.",
"channel.connectionError.permission_denied": "The platform denied access. Check the bot's permissions and enabled capabilities.",
"channel.connectionError.rate_limited": "The platform is rate limiting this bot. Wait a moment and try again.",
- "channel.connectionError.session_expired": "The bot session has expired. Save the channel again to reconnect it.",
+ "channel.connectionError.session_expired": "The bot session has expired. Save the bot again to reconnect it.",
"channel.connectionError.upstream_unavailable": "The platform service is temporarily unavailable. LobeHub will try again later.",
"channel.connectionMode": "Connection Mode",
"channel.connectionModeHint": "How the platform delivers events to the bot",
@@ -116,18 +144,13 @@
"channel.copied": "Copied to clipboard",
"channel.copy": "Copy",
"channel.credentials": "Credentials",
- "channel.dangerZone.removeDesc": "Delete this channel's credentials and settings, and disconnect the bot from {{name}}. This cannot be undone.",
- "channel.dangerZone.resetConfirm": "Reset every setting except the credentials to its default? Takes effect after you save.",
- "channel.dangerZone.resetDesc": "Restore every setting except the credentials to its default. Takes effect after you save.",
"channel.debounceMs": "Wait Window (ms)",
"channel.debounceMsHint": "How long to wait for additional messages before dispatching to the agent (ms)",
- "channel.deleteAllChannels": "Remove All Channels",
- "channel.deleteAllConfirmDesc": "This action will permanently remove all message channels and their configurations for this agent. This cannot be undone.",
- "channel.deleteAllFailed": "Failed to remove all channels",
+ "channel.deleteAllChannels": "Remove All IM Bots",
+ "channel.deleteAllConfirmDesc": "This action will permanently remove all bots and their configurations for this agent. This cannot be undone.",
+ "channel.deleteAllFailed": "Failed to remove all bots",
"channel.deleteAllSuccess": "All channels removed",
- "channel.deleteConfirmDesc": "This action will permanently remove this message channel and its configuration. This cannot be undone.",
- "channel.detailDesc": "Connect a {{name}} bot so {{agent}} can receive and reply to messages in {{name}}.",
- "channel.detailDescAgentFallback": "this agent",
+ "channel.deleteConfirmDesc": "This action will permanently remove this bot and its configuration. This cannot be undone.",
"channel.devWebhookProxyUrl": "HTTPS Tunnel URL",
"channel.devWebhookProxyUrlHint": "Optional. HTTPS tunnel URL for forwarding webhook requests to local dev server.",
"channel.discard": "Discard",
@@ -159,8 +182,12 @@
"channel.feishu.fetchOwnerIdFailed": "Failed to read the app owner",
"channel.feishu.fetchOwnerIdMissingCredentials": "Enter the Application ID and App Secret first — the lookup runs as your app.",
"channel.feishu.fetchOwnerIdSuccess": "Open ID filled in — check it is you, then save",
- "channel.feishu.webhookMigrationDesc": "WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.",
+ "channel.feishu.webhookMigrationDesc": "WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket under Connection options on the Connect tab. No additional configuration is needed on the Feishu/Lark Open Platform.",
"channel.feishu.webhookMigrationTitle": "Consider migrating to WebSocket mode",
+ "channel.group.connection": "Connection options",
+ "channel.group.credentialsDesc": "Encrypted when saved, and shown masked afterwards.",
+ "channel.group.credentialsOptional": "Optional credentials",
+ "channel.group.setup": "Get started",
"channel.groupAllowFrom": "Allowed Channels",
"channel.groupAllowFromAdd": "Add channel",
"channel.groupAllowFromEmpty": "No channels added yet — the bot will not respond anywhere.",
@@ -187,10 +214,13 @@
"channel.guestPolicyOpenHint": "Accept Guest Mode summons from anyone",
"channel.guestPolicyPairing": "Pairing",
"channel.guestPolicyPairingHint": "Strangers need /approve to use Guest Mode",
+ "channel.hero.connected": "{{agent}} · app ID {{id}}",
+ "channel.hero.new": "Once connected, {{agent}} can work in {{name}}.",
+ "channel.hero.title": "{{name}} bot",
"channel.historyLimit": "History Message Limit",
"channel.historyLimitHint": "Default number of messages to fetch when reading channel history",
- "channel.home.title": "Chat with <avatar/>{{name}} on Your Favorite App",
- "channel.imessage.applicationIdHint": "A stable identifier shared by the cloud channel and the Desktop bridge.",
+ "channel.home.title": "Chat with <avatar/>{{name}} on Your Favorite Chat App",
+ "channel.imessage.applicationIdHint": "A stable identifier shared by the cloud bot and the Desktop bridge.",
"channel.imessage.applicationIdPlaceholder": "e.g. home-mac-mini",
"channel.imessage.blueBubblesPassword": "BlueBubbles Password",
"channel.imessage.blueBubblesPasswordHint": "Stored locally in LobeHub Desktop and used only to call the local BlueBubbles server.",
@@ -257,15 +287,15 @@
"channel.paidFeature.badge": "Pro",
"channel.paidFeature.cta.personal": "Upgrade",
"channel.paidFeature.cta.workspace": "Upgrade",
- "channel.paidFeature.desc": "{{name}} is available on paid plans. Upgrade to any paid plan to configure and keep this channel connected.",
- "channel.paidFeature.enforce.desc": "{{name}} is available on paid plans. Upgrade to a paid personal plan or a Pro / Business workspace to configure and keep this channel connected.",
- "channel.paidFeature.enforce.desc.personal": "{{name}} is available on paid personal plans. Upgrade to configure and keep this channel connected.",
- "channel.paidFeature.enforce.desc.workspace": "{{name}} is available on Pro / Business workspaces. Upgrade this workspace to configure and keep this channel connected.",
+ "channel.paidFeature.desc": "{{name}} is available on paid plans. Upgrade to any paid plan to configure and keep this bot connected.",
+ "channel.paidFeature.enforce.desc": "{{name}} is available on paid plans. Upgrade to a paid personal plan or a Pro / Business workspace to configure and keep this bot connected.",
+ "channel.paidFeature.enforce.desc.personal": "{{name}} is available on paid personal plans. Upgrade to configure and keep this bot connected.",
+ "channel.paidFeature.enforce.desc.workspace": "{{name}} is available on Pro / Business workspaces. Upgrade this workspace to configure and keep this bot connected.",
"channel.paidFeature.enforce.title": "Paid plan required",
"channel.paidFeature.fieldLocked": "Available on paid plans. Upgrade to configure this feature.",
- "channel.paidFeature.notice.desc": "Due to the high communication costs for the {{name}} channel, we plan to make this channel a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this channel now requires a paid personal plan or a Pro / Business workspace.",
- "channel.paidFeature.notice.desc.personal": "Due to the high communication costs for the {{name}} channel, we plan to make this channel a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this channel requires a paid personal plan.",
- "channel.paidFeature.notice.desc.workspace": "Due to the high communication costs for the {{name}} channel, we plan to make this channel a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this channel requires upgrading this workspace to Pro or Business.",
+ "channel.paidFeature.notice.desc": "Due to the high communication costs for the {{name}} bot, we plan to make this bot a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this bot now requires a paid personal plan or a Pro / Business workspace.",
+ "channel.paidFeature.notice.desc.personal": "Due to the high communication costs for the {{name}} bot, we plan to make this bot a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this bot requires a paid personal plan.",
+ "channel.paidFeature.notice.desc.workspace": "Due to the high communication costs for the {{name}} bot, we plan to make this bot a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this bot requires upgrading this workspace to Pro or Business.",
"channel.paidFeature.notice.title": "{{name}} will soon require a paid plan",
"channel.paidFeature.noticeBadge": "Pro soon",
"channel.paidFeature.title": "Paid plan required",
@@ -287,8 +317,10 @@
"channel.publicKeyPlaceholder": "64-character hex string",
"channel.qq.appIdHint": "Your QQ Bot App ID from QQ Open Platform",
"channel.qq.description": "Connect this agent to QQ for group chats and direct messages.",
- "channel.qq.webhookMigrationDesc": "WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket in Advanced Settings.",
+ "channel.qq.webhookMigrationDesc": "WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket under Connection options on the Connect tab.",
"channel.qq.webhookMigrationTitle": "Consider migrating to WebSocket mode",
+ "channel.quickSetup.connect.desc": "Saves what you filled in above and brings the bot online. Everything else can be changed later.",
+ "channel.quickSetup.connect.title": "Save and connect",
"channel.quickSetup.discord.bot.desc": "On the Bot page, Reset Token and copy it, then turn on Message Content Intent.",
"channel.quickSetup.discord.bot.title": "Get the bot token and allow message content",
"channel.quickSetup.discord.create.desc": "In the Developer Portal, click New Application and name it.",
@@ -305,8 +337,8 @@
"channel.quickSetup.feishu.events.title": "Subscribe to messages",
"channel.quickSetup.feishu.publish.desc": "Permission changes take effect once published.",
"channel.quickSetup.feishu.publish.title": "Publish a version",
- "channel.quickSetup.feishu.scan.brandMismatch.feishu": "This app was created with a Feishu account. Connect it from the Feishu channel instead.",
- "channel.quickSetup.feishu.scan.brandMismatch.lark": "This app was created with a Lark account. Connect it from the Lark channel instead.",
+ "channel.quickSetup.feishu.scan.brandMismatch.feishu": "This app was created with a Feishu account. Connect it as a Feishu bot instead.",
+ "channel.quickSetup.feishu.scan.brandMismatch.lark": "This app was created with a Lark account. Connect it as a Lark bot instead.",
"channel.quickSetup.feishu.scan.created": "App created. Connecting…",
"channel.quickSetup.feishu.scan.denied": "Creation was declined in Feishu.",
"channel.quickSetup.feishu.scan.does.app": "Creates the app with the bot capability turned on",
@@ -323,7 +355,6 @@
"channel.quickSetup.feishu.scan.saveFailed": "The app was created but couldn't be saved. Keep these credentials and save again.",
"channel.quickSetup.feishu.scan.title": "Scan with Feishu to create the bot",
"channel.quickSetup.feishu.scan.waiting": "Waiting for you to confirm in Feishu…",
- "channel.quickSetup.guideDesc": "Create the bot in {{name}}, then paste its credentials under Connection.",
"channel.quickSetup.guideTitle": "Setup steps",
"channel.quickSetup.line.account.desc": "Sign in with your LINE Business ID and create the account the bot speaks as.",
"channel.quickSetup.line.account.title": "Create a LINE Official Account",
@@ -360,6 +391,26 @@
"channel.quickSetup.telegram.privacy.title": "Let it read group messages (optional)",
"channel.quickSetup.telegram.token.desc": "BotFather replies with a token like 1234567890:ABC… — paste it here.",
"channel.quickSetup.telegram.token.title": "Copy the token",
+ "channel.quickView.answer": "Three things came up today: the release moved to Thursday, the sign-in page copy, and the priority of the bug list. Want me to turn them into to-dos?",
+ "channel.quickView.ask": "Summarize today's discussion",
+ "channel.quickView.askDm": "Can you summarize today's discussion?",
+ "channel.quickView.bot": "Bot",
+ "channel.quickView.collapse": "Collapse preview",
+ "channel.quickView.desc": "How the bot behaves in chat with the settings as they are now, before you save. Illustrative.",
+ "channel.quickView.dm.allowlist": "Sorry, you aren't authorized to send direct messages to this bot. Please contact the bot's owner if you need access.",
+ "channel.quickView.dm.disabled": "This bot isn't accepting direct messages. Please reach out by mentioning it in a shared channel or group instead.",
+ "channel.quickView.dm.pairing": "To DM this bot, send this pairing code to the bot's owner: 7K2F. They run /approve 7K2F to grant you access. The code expires in 1 hour.",
+ "channel.quickView.group.allowlist": "This bot isn't enabled in this channel. Please contact the bot's owner if you need access.",
+ "channel.quickView.group.disabled": "This bot doesn't respond in groups or channels. Please reach out via direct message instead.",
+ "channel.quickView.groupAllowlist": "Replies only in the groups on your list.",
+ "channel.quickView.keywords": "Also wakes on {{keywords}} without an @mention.",
+ "channel.quickView.open": "Preview",
+ "channel.quickView.sceneDm": "Direct message",
+ "channel.quickView.sceneGroup": "Group",
+ "channel.quickView.sender.rejected": "Sorry, you aren't authorized to interact with this bot. Please contact the bot's owner if you need access.",
+ "channel.quickView.stranger": "Someone new",
+ "channel.quickView.title": "Quick view",
+ "channel.quickView.toolCall": "Read 12 earlier messages",
"channel.reactionMode": "Status Reactions",
"channel.reactionModeFull": "Detailed",
"channel.reactionModeFullHint": "Also switch between thinking and working after every step",
@@ -369,16 +420,15 @@
"channel.reactionModeNone": "Off",
"channel.reactionModeNoneHint": "Never add status reactions",
"channel.refreshStatus": "Refresh status",
- "channel.removeChannel": "Remove Channel",
- "channel.removeFailed": "Failed to remove channel",
- "channel.removed": "Channel removed",
+ "channel.removeChannel": "Remove IM Bot",
+ "channel.removeFailed": "Failed to remove bot",
+ "channel.removed": "Bot removed",
+ "channel.reply.instant": "Changes here take effect as soon as you make them. There is nothing to save.",
"channel.resultDetail.hide": "Hide details",
"channel.resultDetail.show": "Show details",
"channel.runtimeDisconnected": "Bot disconnected",
"channel.save": "Save Configuration",
- "channel.saveAndConnect": "Save and Connect",
- "channel.saveBar.firstSave": "The bot connects as soon as you save.",
- "channel.saveBar.unsaved": "You have unsaved changes",
+ "channel.saveAndConnect": "Save and connect",
"channel.saveFailed": "Failed to save configuration",
"channel.saveFailedHint": "Check the fields above and try again.",
"channel.saveFirstWarning": "Please save configuration first",
@@ -386,23 +436,12 @@
"channel.secretToken": "Webhook Secret Token",
"channel.secretTokenHint": "Used to verify webhook requests from Telegram. Leave blank and LobeHub derives one for this bot — verification is always on.",
"channel.secretTokenPlaceholder": "Leave blank to auto-generate",
- "channel.section.access.desc": "Who can talk to the bot, and where it responds.",
- "channel.section.access.title": "Access",
- "channel.section.account.desc": "Which {{name}} account is yours. The agent uses it to reach you and to approve pairing requests.",
- "channel.section.account.title": "Your account",
- "channel.section.connection.desc": "Credentials the bot uses to sign in to {{name}}.",
- "channel.section.connection.title": "Connection",
- "channel.section.danger.title": "Danger zone",
- "channel.section.other.title": "Other",
- "channel.section.replies.desc": "How the bot handles messages that arrive together, and what its replies include.",
- "channel.section.replies.title": "Replies",
- "channel.section.wake.desc": "When the bot steps in without an @mention.",
- "channel.section.wake.title": "Wake-up",
"channel.serverId": "Default Server ID",
- "channel.serverIdHint": "Default server / guild AI tools act on; not used for access control",
+ "channel.serverIdHint": "When the bot uses its tools (looking up channels, reading or sending messages) without being told which server, it works in this one. It does not decide where the bot replies.",
"channel.serverIdHint.discord": "Enable Developer Mode (Settings → Advanced), then right-click the server icon → Copy Server ID.",
"channel.serverIdHint.slack": "Workspace ID (starts with T). Find it under Settings & administration → Workspace settings, or in the workspace URL.",
"channel.settings": "Advanced Settings",
+ "channel.settingsResetConfirm": "Are you sure you want to reset advanced settings to default?",
"channel.settingsResetDefault": "Reset to Default",
"channel.setupGuide": "Setup Guide",
"channel.showUsageStats": "Show Usage Stats",
@@ -413,7 +452,7 @@
"channel.slack.appToken": "App-Level Token",
"channel.slack.appTokenHint": "Required for Socket Mode (WebSocket). Generate an app-level token (xapp-...) under Basic Information in your Slack app settings.",
"channel.slack.description": "Connect this agent to Slack for channel conversations and direct messages.",
- "channel.slack.webhookMigrationDesc": "Socket Mode provides real-time event delivery via WebSocket without exposing a public HTTP endpoint. To migrate, enable Socket Mode in your Slack app settings, generate an App-Level Token, then switch the Connection Mode to WebSocket in Advanced Settings.",
+ "channel.slack.webhookMigrationDesc": "Socket Mode provides real-time event delivery via WebSocket without exposing a public HTTP endpoint. To migrate, enable Socket Mode in your Slack app settings, generate an App-Level Token, then switch the Connection Mode to WebSocket under Connection options on the Connect tab.",
"channel.slack.webhookMigrationTitle": "Consider migrating to Socket Mode (WebSocket)",
"channel.statusConnected": "Connected",
"channel.statusDisconnected": "Disconnected",
@@ -421,6 +460,11 @@
"channel.statusFailed": "Failed",
"channel.statusQueued": "Queued",
"channel.statusStarting": "Starting",
+ "channel.tab.access": "Access",
+ "channel.tab.advanced": "Advanced",
+ "channel.tab.connect": "Connect",
+ "channel.tab.reply": "Replies",
+ "channel.tab.wake": "Wake policy",
"channel.telegram.description": "Connect this agent to Telegram for private and group chats.",
"channel.testConnection": "Test Connection",
"channel.testFailed": "Connection test failed",
@@ -436,13 +480,13 @@
"channel.userIdHint.qq": "Your QQ number, shown on your QQ profile page.",
"channel.userIdHint.slack": "Open your Slack profile → ⋮ More → Copy member ID (starts with U).",
"channel.userIdHint.telegram": "Send any message to @userinfobot on Telegram — it replies with your numeric User ID.",
- "channel.userIdMissingAction": "Add User ID",
- "channel.userIdMissingHint": "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in under Your account.",
+ "channel.userIdMissingDesc": "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in on the Access tab.",
"channel.userIdMissingTitle": "Add your platform User ID",
"channel.validationError": "Please fill in Application ID and Token",
"channel.verificationToken": "Verification Token",
"channel.verificationTokenHint": "Optional. Used to verify webhook event source.",
"channel.verificationTokenPlaceholder": "Paste your verification token here",
+ "channel.wake.intro": "Decides whether the bot may answer a message nobody addressed to it: a watch keyword in a thread it was not mentioned in, or a message continuing a conversation it already joined. Plain channel chatter is only judged and recorded, never answered.",
"channel.watchKeywordInstructionLabel": "Instruction",
"channel.watchKeywordInstructionPlaceholder": "e.g. Scan the recent thread and reply if there is an actionable bug report",
"channel.watchKeywordLabel": "Keyword",
@@ -683,7 +727,7 @@
"share.visitor.upload.fileTooLarge": "Files must be under {{max}}.",
"share.visitor.upload.tooManyFiles": "You can attach up to {{max}} files per message.",
"transfer.button": "Move",
- "transfer.confirm.botChannels": "Bot channel connections may need to be refreshed after moving",
+ "transfer.confirm.botChannels": "Bot connections may need to be refreshed after moving",
"transfer.confirm.chatGroups": "Multi-agent group associations will be removed",
"transfer.confirm.desc": "This will move the agent and all associated data (topics, messages, files, etc.) to the target workspace.",
"transfer.confirm.plugins": "Custom plugins may not be available in the target workspace",
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 2ecda9a2106..ad70ee5e844 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2281,7 +2281,7 @@
"supervisor.todoList.allComplete": "All tasks completed",
"supervisor.todoList.title": "Tasks Completed",
"tab.groupProfile": "Group Profile",
- "tab.integration": "Channels",
+ "tab.integration": "IM Bots",
"tab.profile": "Agent Profile",
"tab.profileBasic": "Profile",
"tab.search": "Search",
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 66184a4a518..6b5df55e359 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -20,7 +20,7 @@
"navigation.agents": "Agents",
"navigation.appMenu": "App menu",
"navigation.apps": "Apps",
- "navigation.channels": "Channels",
+ "navigation.channels": "IM Bots",
"navigation.chat": "Chat",
"navigation.dashboard": "Dashboards",
"navigation.discover": "Discover",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 97fdc0a27c5..571e740bd1c 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -3269,8 +3269,8 @@
"workspace.onboarding.flow.assistant.hint": "💡 This assistant is shared by the whole team. Members can @ it in chats and group chats.",
"workspace.onboarding.flow.channels.connect.attempt": "Attempt {{count}}",
"workspace.onboarding.flow.channels.connect.back": "Back to list",
- "workspace.onboarding.flow.channels.connect.category": "Bot channel",
- "workspace.onboarding.flow.channels.connect.connectedDesc": "Members can now @{{name}} in your group to hand off work. Change it anytime in Agent → Channels.",
+ "workspace.onboarding.flow.channels.connect.category": "IM Bot",
+ "workspace.onboarding.flow.channels.connect.connectedDesc": "Members can now @{{name}} in your group to hand off work. Change it anytime in Agent → IM Bots.",
"workspace.onboarding.flow.channels.connect.connectedTitle": "{{name}} connected",
"workspace.onboarding.flow.channels.connect.description": "Use your own {{platform}} app to bring {{name}} into your team's chats as a bot.",
"workspace.onboarding.flow.channels.connect.edit": "Edit credentials",
@@ -3290,10 +3290,10 @@
"workspace.onboarding.flow.channels.connect.verifying": "Checking the credentials with the platform…",
"workspace.onboarding.flow.channels.description": "Connect a bot your team owns to {{name}}. Everyone in the group can @{{name}} to hand off work — nobody has to link an account.",
"workspace.onboarding.flow.channels.highlight": "and anyone can hand me work.",
- "workspace.onboarding.flow.channels.more": "You can change channels anytime in Agent → Channels.",
+ "workspace.onboarding.flow.channels.more": "You can change IM bots anytime in Agent → IM Bots.",
"workspace.onboarding.flow.channels.quote": "Add me to your team's group chats,",
"workspace.onboarding.flow.channels.showLess": "Show less",
- "workspace.onboarding.flow.channels.showMore": "More channels ({{count}})",
+ "workspace.onboarding.flow.channels.showMore": "More IM bots ({{count}})",
"workspace.onboarding.flow.channels.title": "Bring the assistant into your team's chats",
"workspace.onboarding.flow.connectApps.apps.confluence": "Reads the team's shared pages to learn your projects, processes and decisions",
"workspace.onboarding.flow.connectApps.apps.github": "Reads the team's repositories and collaboration to learn your stack and who works on what",
diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.json
index daca36d6ea6..067d47280f7 100644
--- a/locales/zh-CN/agent.json
+++ b/locales/zh-CN/agent.json
@@ -1,4 +1,33 @@
{
+ "channel.access.dm.approval": "陌生人需要我批准",
+ "channel.access.dm.approvalDesc": "陌生人会收到配对码,你用 /approve 批准后才能使用。",
+ "channel.access.dm.closed": "不接受私聊",
+ "channel.access.dm.closedDesc": "不处理私聊,会引导对方去群聊里 @ 它。",
+ "channel.access.dm.everyone": "所有人",
+ "channel.access.dm.everyoneDesc": "任何人都可以直接私聊它。",
+ "channel.access.dm.label": "谁可以私聊它",
+ "channel.access.dm.listed": "仅名单内的人",
+ "channel.access.dm.listedDesc": "只有名单里的人能使用,其他人会被拒绝。",
+ "channel.access.group.allowlist": "仅指定的群聊",
+ "channel.access.group.allowlistDesc": "只在你列在下面的群聊里回复。",
+ "channel.access.group.disabled": "不在群聊里响应",
+ "channel.access.group.disabledDesc": "不处理群聊消息,会引导对方私聊。",
+ "channel.access.group.label": "在群聊和频道里怎么响应",
+ "channel.access.group.listNote": "上面的名单在群聊里也生效:只有名单里的人能在群聊里使用它。",
+ "channel.access.group.open": "所有群聊和频道",
+ "channel.access.group.openDesc": "被 @ 时就会回复。",
+ "channel.access.identity.approverMissing": "要批准陌生人,需要先填你自己的 ID,否则没有人能执行 /approve。",
+ "channel.access.identity.desc": "用于主动联系你(提醒、通知),也是批准陌生人的人。下面的设置不会限制你自己。",
+ "channel.access.identity.required": "批准陌生人需要填写你的 ID",
+ "channel.access.list.approved": "已批准的人",
+ "channel.access.list.clearContent": "改成「所有人」会同时移除名单里的 {{count}} 个人,因为名单一旦有人,就会限制所有人。",
+ "channel.access.list.clearOk": "切换并清空",
+ "channel.access.list.clearTitle": "清空名单?",
+ "channel.access.list.emptyApproval": "还没有批准任何人。陌生人私聊时会收到配对码。",
+ "channel.access.list.emptyListed": "名单还是空的,除了你自己,现在没有人能私聊它。",
+ "channel.access.list.hint": "名单在私聊和群聊里都生效:只有名单里的人能使用它。",
+ "channel.access.list.listed": "名单内的人",
+ "channel.access.recommended": "推荐",
"channel.allowFrom": "允许的用户",
"channel.allowFromAdd": "添加用户",
"channel.allowFromEmpty": "尚未添加任何用户——任何人都可以与机器人交互。",
@@ -78,7 +107,6 @@
"channel.botWakeScopeNoneHint": "机器人不会主动插话。",
"channel.botWakeWindowSeconds": "跟进窗口(秒)",
"channel.botWakeWindowSecondsHint": "机器人发言后,这段时间内同一位置的普通消息会被视为对它的跟进。",
- "channel.channelListLimit": "列表最多包含 {{max}} 个条目 — 请先移除一个。",
"channel.charLimit": "字符限制",
"channel.charLimitHint": "单条消息的最大字符数",
"channel.comingSoon": "即将上线",
@@ -102,10 +130,10 @@
"channel.connectionError.application_not_found": "机器人应用不存在,请检查平台控制台中的应用 ID。",
"channel.connectionError.connection_closed": "平台连接已中断,LobeHub 将自动尝试重连。",
"channel.connectionError.invalid_credentials": "机器人凭据无效,请检查应用 ID、密钥和访问令牌。",
- "channel.connectionError.missing_credentials": "缺少必要的机器人凭据,请补全频道配置后重试。",
+ "channel.connectionError.missing_credentials": "缺少必要的机器人凭据,请补全 Bot 配置后重试。",
"channel.connectionError.permission_denied": "平台拒绝了访问,请检查机器人的权限和已启用能力。",
"channel.connectionError.rate_limited": "平台正在限制该机器人的请求频率,请稍后重试。",
- "channel.connectionError.session_expired": "机器人会话已过期,请重新保存频道配置以建立连接。",
+ "channel.connectionError.session_expired": "机器人会话已过期,请重新保存 Bot 配置以建立连接。",
"channel.connectionError.upstream_unavailable": "平台服务暂时不可用,LobeHub 稍后会自动重试。",
"channel.connectionMode": "连接模式",
"channel.connectionModeHint": "平台向机器人推送事件的方式",
@@ -116,18 +144,13 @@
"channel.copied": "已复制到剪贴板",
"channel.copy": "复制",
"channel.credentials": "凭证配置",
- "channel.dangerZone.removeDesc": "删除这个频道的凭证和设置,并断开机器人与 {{name}} 的连接。此操作无法撤销。",
- "channel.dangerZone.resetConfirm": "确定把凭证以外的所有设置恢复为默认值吗?保存后生效。",
- "channel.dangerZone.resetDesc": "把凭证以外的所有设置恢复为默认值,保存后生效。",
"channel.debounceMs": "等待窗口(毫秒)",
"channel.debounceMsHint": "在派发给 Agent 之前等待更多消息的时间(毫秒)",
- "channel.deleteAllChannels": "移除所有频道",
- "channel.deleteAllConfirmDesc": "此操作将永久移除该助手的所有消息频道及其配置,且无法撤销。",
- "channel.deleteAllFailed": "移除所有频道失败",
- "channel.deleteAllSuccess": "所有频道已移除",
- "channel.deleteConfirmDesc": "此操作将永久移除该消息频道及其配置,且无法撤销。",
- "channel.detailDesc": "连接 {{name}} 机器人,让 {{agent}} 在 {{name}} 里接收和回复消息。",
- "channel.detailDescAgentFallback": "这个 Agent",
+ "channel.deleteAllChannels": "移除所有 IM 机器人",
+ "channel.deleteAllConfirmDesc": "此操作将永久移除该助手的所有 Bot 及其配置,且无法撤销。",
+ "channel.deleteAllFailed": "移除所有 Bot 失败",
+ "channel.deleteAllSuccess": "所有 Bot 已移除",
+ "channel.deleteConfirmDesc": "此操作将永久移除该 Bot 及其配置,且无法撤销。",
"channel.devWebhookProxyUrl": "HTTPS 隧道地址",
"channel.devWebhookProxyUrlHint": "可选。用于将 webhook 请求转发到本地开发服务器的 HTTPS 隧道 URL。",
"channel.discard": "放弃更改",
@@ -159,8 +182,12 @@
"channel.feishu.fetchOwnerIdFailed": "读取应用所有者失败",
"channel.feishu.fetchOwnerIdMissingCredentials": "请先填写应用 ID 和 App Secret,查询以你的应用身份发起。",
"channel.feishu.fetchOwnerIdSuccess": "已填入 Open ID,确认是你本人后保存",
- "channel.feishu.webhookMigrationDesc": "WebSocket 模式提供实时事件推送,无需配置公网回调地址。如需迁移,在高级设置中将连接模式切换为 WebSocket 即可,无需在飞书/Lark 开放平台进行额外配置。",
+ "channel.feishu.webhookMigrationDesc": "WebSocket 模式提供实时事件推送,无需配置公网回调地址。如需迁移,在「接入」的连接选项中将连接模式切换为 WebSocket 即可,无需在飞书/Lark 开放平台进行额外配置。",
"channel.feishu.webhookMigrationTitle": "建议迁移到 WebSocket 模式",
+ "channel.group.connection": "连接选项",
+ "channel.group.credentialsDesc": "凭证加密保存,保存后只显示打码的值。",
+ "channel.group.credentialsOptional": "可选凭证",
+ "channel.group.setup": "开始接入",
"channel.groupAllowFrom": "允许的频道",
"channel.groupAllowFromAdd": "添加频道",
"channel.groupAllowFromEmpty": "尚未添加任何频道——机器人不会在任何地方响应。",
@@ -187,10 +214,13 @@
"channel.guestPolicyOpenHint": "接受任何人的访客模式召唤",
"channel.guestPolicyPairing": "配对审批",
"channel.guestPolicyPairingHint": "陌生人需经 /approve 审批后才能使用访客模式",
+ "channel.hero.connected": "{{agent}} · 应用 ID {{id}}",
+ "channel.hero.new": "接入后,{{agent}} 就能在 {{name}} 里工作。",
+ "channel.hero.title": "{{name}} 机器人",
"channel.historyLimit": "历史消息条数",
"channel.historyLimitHint": "读取频道历史消息时默认获取的消息数量",
- "channel.home.title": "在你喜爱的应用中与 <avatar/>{{name}} 聊天",
- "channel.imessage.applicationIdHint": "云端渠道和桌面端桥接共同使用的稳定标识。",
+ "channel.home.title": "在你喜爱的聊天软件中与 <avatar/>{{name}} 聊天",
+ "channel.imessage.applicationIdHint": "云端 Bot 和桌面端桥接共同使用的稳定标识。",
"channel.imessage.applicationIdPlaceholder": "例如 home-mac-mini",
"channel.imessage.blueBubblesPassword": "BlueBubbles 密码",
"channel.imessage.blueBubblesPasswordHint": "仅保存在 LobeHub Desktop 本地,用于访问本机 BlueBubbles Server。",
@@ -257,15 +287,15 @@
"channel.paidFeature.badge": "Pro",
"channel.paidFeature.cta.personal": "Upgrade",
"channel.paidFeature.cta.workspace": "Upgrade",
- "channel.paidFeature.desc": "{{name}} 仅面向付费 Plan 开放。升级到任意付费 Plan 后即可配置并保持该渠道连接。",
- "channel.paidFeature.enforce.desc": "{{name}} 仅面向付费 Plan 开放。升级到个人付费 Plan,或使用 Pro / Business Workspace 后,即可配置并保持该渠道连接。",
- "channel.paidFeature.enforce.desc.personal": "{{name}} 仅面向个人付费 Plan 开放。升级后即可配置并保持该渠道连接。",
- "channel.paidFeature.enforce.desc.workspace": "{{name}} 仅面向 Pro / Business Workspace 开放。升级当前 Workspace 后即可配置并保持该渠道连接。",
+ "channel.paidFeature.desc": "{{name}} 仅面向付费 Plan 开放。升级到任意付费 Plan 后即可配置并保持该 Bot 连接。",
+ "channel.paidFeature.enforce.desc": "{{name}} 仅面向付费 Plan 开放。升级到个人付费 Plan,或使用 Pro / Business Workspace 后,即可配置并保持该 Bot 连接。",
+ "channel.paidFeature.enforce.desc.personal": "{{name}} 仅面向个人付费 Plan 开放。升级后即可配置并保持该 Bot 连接。",
+ "channel.paidFeature.enforce.desc.workspace": "{{name}} 仅面向 Pro / Business Workspace 开放。升级当前 Workspace 后即可配置并保持该 Bot 连接。",
"channel.paidFeature.enforce.title": "需要付费 Plan",
"channel.paidFeature.fieldLocked": "仅面向付费 Plan 开放,升级后即可配置该功能。",
- "channel.paidFeature.notice.desc": "由于 {{name}} 渠道通信成本过高,我们计划近期将该渠道调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接该渠道需要升级到个人付费 Plan,或使用 Pro / Business Workspace。",
- "channel.paidFeature.notice.desc.personal": "由于 {{name}} 渠道通信成本过高,我们计划近期将该渠道调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接该渠道需要升级到个人付费 Plan。",
- "channel.paidFeature.notice.desc.workspace": "由于 {{name}} 渠道通信成本过高,我们计划近期将该渠道调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接该渠道需要升级当前 Workspace 到 Pro 或 Business。",
+ "channel.paidFeature.notice.desc": "由于 {{name}} Bot 通信成本过高,我们计划近期将该 Bot 调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接该 Bot 需要升级到个人付费 Plan,或使用 Pro / Business Workspace。",
+ "channel.paidFeature.notice.desc.personal": "由于 {{name}} Bot 通信成本过高,我们计划近期将该 Bot 调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接该 Bot 需要升级到个人付费 Plan。",
+ "channel.paidFeature.notice.desc.workspace": "由于 {{name}} Bot 通信成本过高,我们计划近期将该 Bot 调整为付费功能。预告期内已有连接可继续使用,但新建或重新连接该 Bot 需要升级当前 Workspace 到 Pro 或 Business。",
"channel.paidFeature.notice.title": "{{name}} 即将调整为付费功能",
"channel.paidFeature.noticeBadge": "即将付费",
"channel.paidFeature.title": "需要付费 Plan",
@@ -287,8 +317,10 @@
"channel.publicKeyPlaceholder": "64 位十六进制字符串",
"channel.qq.appIdHint": "您在 QQ 开放平台获取的机器人 App ID",
"channel.qq.description": "将助手连接到 QQ,支持群聊和私聊。",
- "channel.qq.webhookMigrationDesc": "WebSocket 模式无需回调 URL,即可提供实时事件传递和自动重连。要进行迁移,请在 QQ 开放平台创建一个新的机器人且不要配置回调 URL,然后在高级设置中将连接模式切换为 WebSocket。",
+ "channel.qq.webhookMigrationDesc": "WebSocket 模式无需回调 URL,即可提供实时事件传递和自动重连。要进行迁移,请在 QQ 开放平台创建一个新的机器人且不要配置回调 URL,然后在「接入」的连接选项中将连接模式切换为 WebSocket。",
"channel.qq.webhookMigrationTitle": "建议迁移至 WebSocket 模式",
+ "channel.quickSetup.connect.desc": "保存上面填好的信息,机器人随即上线。其他设置之后随时可以改。",
+ "channel.quickSetup.connect.title": "保存并连接",
"channel.quickSetup.discord.bot.desc": "在 Bot 页面点 Reset Token 并复制,然后打开 Message Content Intent。",
"channel.quickSetup.discord.bot.title": "获取 Bot Token 并允许读取消息内容",
"channel.quickSetup.discord.create.desc": "在开发者后台点 New Application 并命名。",
@@ -305,8 +337,8 @@
"channel.quickSetup.feishu.events.title": "订阅消息事件",
"channel.quickSetup.feishu.publish.desc": "权限变更需发布后才生效。",
"channel.quickSetup.feishu.publish.title": "发布版本",
- "channel.quickSetup.feishu.scan.brandMismatch.feishu": "这个应用是用飞书账号创建的,请在飞书渠道中接入。",
- "channel.quickSetup.feishu.scan.brandMismatch.lark": "这个应用是用 Lark 账号创建的,请在 Lark 渠道中接入。",
+ "channel.quickSetup.feishu.scan.brandMismatch.feishu": "这个应用是用飞书账号创建的,请改用飞书 Bot 接入。",
+ "channel.quickSetup.feishu.scan.brandMismatch.lark": "这个应用是用 Lark 账号创建的,请改用 Lark Bot 接入。",
"channel.quickSetup.feishu.scan.created": "应用已创建,正在连接…",
"channel.quickSetup.feishu.scan.denied": "已在飞书中取消创建。",
"channel.quickSetup.feishu.scan.does.app": "自动创建应用并开启机器人能力",
@@ -323,7 +355,6 @@
"channel.quickSetup.feishu.scan.saveFailed": "应用已创建,但保存失败。请保留以下凭据并重新保存。",
"channel.quickSetup.feishu.scan.title": "用飞书扫码,一键创建机器人",
"channel.quickSetup.feishu.scan.waiting": "等待你在飞书中确认…",
- "channel.quickSetup.guideDesc": "先在 {{name}} 创建机器人,再把凭证填到下方「连接」中。",
"channel.quickSetup.guideTitle": "设置步骤",
"channel.quickSetup.line.account.desc": "用 LINE Business ID 登录,创建机器人对外使用的官方账号。",
"channel.quickSetup.line.account.title": "创建 LINE 官方账号",
@@ -360,6 +391,26 @@
"channel.quickSetup.telegram.privacy.title": "允许读取群消息(可选)",
"channel.quickSetup.telegram.token.desc": "BotFather 会回复形如 1234567890:ABC… 的 Token,粘贴到这里即可。",
"channel.quickSetup.telegram.token.title": "复制 Token",
+ "channel.quickView.answer": "今天主要讨论了三件事:发布时间调整到周四、登录页的文案,以及 bug 列表的优先级。需要我整理成待办吗?",
+ "channel.quickView.ask": "帮我总结一下今天的讨论",
+ "channel.quickView.askDm": "能帮我总结一下今天的讨论吗?",
+ "channel.quickView.bot": "机器人",
+ "channel.quickView.collapse": "收起预览",
+ "channel.quickView.desc": "按当前设置,机器人在聊天里会这样表现,保存前也会实时更新。仅为示意。",
+ "channel.quickView.dm.allowlist": "抱歉,您没有私信该机器人的权限。如需访问请联系机器人管理员。",
+ "channel.quickView.dm.disabled": "该机器人不接受私信。请在共享频道或群组里 @它来联系。",
+ "channel.quickView.dm.pairing": "若要私信该机器人,请把以下配对码发给机器人管理员:7K2F,他们将通过 /approve 7K2F 命令为你授权。配对码 1 小时后失效。",
+ "channel.quickView.group.allowlist": "该机器人未在此频道启用。如需访问请联系机器人管理员。",
+ "channel.quickView.group.disabled": "该机器人不在群组或频道中响应。请通过私信联系。",
+ "channel.quickView.groupAllowlist": "只会在名单内的群聊里回复。",
+ "channel.quickView.keywords": "消息里出现 {{keywords}} 时,不用 @ 也会唤醒它。",
+ "channel.quickView.open": "预览",
+ "channel.quickView.sceneDm": "私聊",
+ "channel.quickView.sceneGroup": "群聊",
+ "channel.quickView.sender.rejected": "抱歉,您没有与该机器人交互的权限。如需访问请联系机器人管理员。",
+ "channel.quickView.stranger": "新成员",
+ "channel.quickView.title": "快速查看",
+ "channel.quickView.toolCall": "读取了 12 条历史消息",
"channel.reactionMode": "状态表情",
"channel.reactionModeFull": "详细",
"channel.reactionModeFullHint": "每一步之后还会在思考与执行之间切换",
@@ -369,16 +420,15 @@
"channel.reactionModeNone": "关闭",
"channel.reactionModeNoneHint": "不添加任何状态表情",
"channel.refreshStatus": "刷新状态",
- "channel.removeChannel": "移除频道",
- "channel.removeFailed": "移除频道失败",
- "channel.removed": "频道已移除",
+ "channel.removeChannel": "移除 IM 机器人",
+ "channel.removeFailed": "移除 Bot 失败",
+ "channel.removed": "Bot 已移除",
+ "channel.reply.instant": "这里的改动一做就生效,不需要再保存。",
"channel.resultDetail.hide": "收起详情",
"channel.resultDetail.show": "查看详情",
"channel.runtimeDisconnected": "机器人已断开连接",
"channel.save": "保存配置",
"channel.saveAndConnect": "保存并连接",
- "channel.saveBar.firstSave": "保存后机器人会立即连接。",
- "channel.saveBar.unsaved": "有未保存的更改",
"channel.saveFailed": "保存配置失败",
"channel.saveFailedHint": "请检查上面的配置项后重试。",
"channel.saveFirstWarning": "请先保存配置",
@@ -386,23 +436,12 @@
"channel.secretToken": "Webhook 密钥",
"channel.secretTokenHint": "用于验证来自 Telegram 的 Webhook 请求。留空则由 LobeHub 为该 bot 自动生成——校验始终开启。",
"channel.secretTokenPlaceholder": "留空则自动生成",
- "channel.section.access.desc": "谁可以和机器人对话,以及它在哪些地方回复。",
- "channel.section.access.title": "访问控制",
- "channel.section.account.desc": "告诉 Agent 哪个 {{name}} 账号是你,用来联系你和审批配对请求。",
- "channel.section.account.title": "你的账号",
- "channel.section.connection.desc": "机器人登录 {{name}} 所用的凭证。",
- "channel.section.connection.title": "连接",
- "channel.section.danger.title": "危险操作",
- "channel.section.other.title": "其他",
- "channel.section.replies.desc": "机器人怎样处理连续发来的消息,以及回复里包含哪些内容。",
- "channel.section.replies.title": "回复方式",
- "channel.section.wake.desc": "机器人在没被 @ 时何时参与对话。",
- "channel.section.wake.title": "唤醒",
"channel.serverId": "默认服务器 ID",
- "channel.serverIdHint": "AI 工具默认作用的服务器 / Guild,与访问控制无关",
+ "channel.serverIdHint": "机器人用工具(查频道、读或发消息)而没被告知是哪个服务器时,就在这个服务器里操作。它不决定机器人在哪里回复。",
"channel.serverIdHint.discord": "在 Discord 设置 → 高级中开启开发者模式,然后右键服务器图标 → 复制服务器 ID。",
"channel.serverIdHint.slack": "Workspace ID(以 T 开头),在 设置与管理 → 工作空间设置 中查看,或从工作空间 URL 中获取。",
"channel.settings": "高级设置",
+ "channel.settingsResetConfirm": "确定要将高级设置恢复为默认配置吗?",
"channel.settingsResetDefault": "恢复默认配置",
"channel.setupGuide": "配置教程",
"channel.showUsageStats": "显示用量统计",
@@ -413,7 +452,7 @@
"channel.slack.appToken": "应用级别 Token",
"channel.slack.appTokenHint": "Socket Mode(WebSocket)所需。在 Slack 应用设置的 Basic Information 中生成应用级别 Token(xapp-...)。",
"channel.slack.description": "将助手连接到 Slack,支持频道对话和私信。",
- "channel.slack.webhookMigrationDesc": "Socket Mode 通过 WebSocket 提供实时事件推送,无需暴露公网 HTTP 端点。如需迁移,请在 Slack 应用设置中启用 Socket Mode,生成应用级别 Token,然后在高级设置中将连接模式切换为 WebSocket。",
+ "channel.slack.webhookMigrationDesc": "Socket Mode 通过 WebSocket 提供实时事件推送,无需暴露公网 HTTP 端点。如需迁移,请在 Slack 应用设置中启用 Socket Mode,生成应用级别 Token,然后在「接入」的连接选项中将连接模式切换为 WebSocket。",
"channel.slack.webhookMigrationTitle": "建议迁移到 Socket Mode(WebSocket)",
"channel.statusConnected": "已连接",
"channel.statusDisconnected": "未连接",
@@ -421,6 +460,11 @@
"channel.statusFailed": "连接失败",
"channel.statusQueued": "排队中",
"channel.statusStarting": "启动中",
+ "channel.tab.access": "访问控制",
+ "channel.tab.advanced": "高级",
+ "channel.tab.connect": "接入",
+ "channel.tab.reply": "回复方式",
+ "channel.tab.wake": "唤醒策略",
"channel.telegram.description": "将助手连接到 Telegram,支持私聊和群聊。",
"channel.testConnection": "测试连接",
"channel.testFailed": "连接测试失败",
@@ -436,13 +480,13 @@
"channel.userIdHint.qq": "你的 QQ 号,在 QQ 资料页可见。",
"channel.userIdHint.slack": "打开 Slack 个人资料 → ⋮ 更多 → 复制 Member ID(以 U 开头)。",
"channel.userIdHint.telegram": "在 Telegram 中给 @userinfobot 发送任意消息,它会回复你的数字 User ID。",
- "channel.userIdMissingAction": "去填写",
- "channel.userIdMissingHint": "未填写时,AI 工具无法主动联系你,配对申请也将无法被批准。给机器人发送 /whoami 即可获取你的 ID,然后在「你的账号」中填写。",
+ "channel.userIdMissingDesc": "未填写时,AI 工具无法主动联系你,配对申请也将无法被批准。给机器人发送 /whoami 即可获取你的 ID,然后在「访问控制」中补充。",
"channel.userIdMissingTitle": "建议补充你的平台用户 ID",
"channel.validationError": "请填写应用 ID 和 Token",
"channel.verificationToken": "Verification Token",
"channel.verificationTokenHint": "可选。用于验证事件推送来源。",
"channel.verificationTokenPlaceholder": "在此粘贴你的 Verification Token",
+ "channel.wake.intro": "决定机器人能否回复没人 @ 它的消息:未被提及的子区里命中监听关键词,或它已参与的对话里继续发来的消息。频道里的普通闲聊只做判断和记录,不会回复。",
"channel.watchKeywordInstructionLabel": "指令",
"channel.watchKeywordInstructionPlaceholder": "如 浏览近期消息,若发现可处理的 bug 报告则回复",
"channel.watchKeywordLabel": "关键词",
@@ -456,7 +500,7 @@
"channel.wechatBotIdHint": "通过二维码授权后分配的机器人标识符。",
"channel.wechatConnectedInfo": "已连接的微信账号",
"channel.wechatGenerateQrCode": "生成二维码",
- "channel.wechatManagedCredentials": "此频道已通过二维码授权连接。凭据由系统自动管理。",
+ "channel.wechatManagedCredentials": "此 Bot 已通过二维码授权连接。凭据由系统自动管理。",
"channel.wechatQrExpired": "二维码已过期,请刷新获取新的二维码。",
"channel.wechatQrLoadFailed": "二维码加载失败,请重试。",
"channel.wechatQrRefresh": "刷新二维码",
@@ -683,7 +727,7 @@
"share.visitor.upload.fileTooLarge": "单个文件不能超过 {{max}}。",
"share.visitor.upload.tooManyFiles": "每条消息最多可附加 {{max}} 个文件。",
"transfer.button": "移动",
- "transfer.confirm.botChannels": "移动后可能需要重新刷新机器人频道连接",
+ "transfer.confirm.botChannels": "移动后可能需要重新刷新机器人连接",
"transfer.confirm.chatGroups": "多助理群组关联将被移除",
"transfer.confirm.desc": "这会把助理及相关数据(话题、消息、文件等)移动到目标工作区。",
"transfer.confirm.plugins": "自定义技能可能无法在目标工作区使用",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 6e604881f99..349b80321bf 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2281,7 +2281,7 @@
"supervisor.todoList.allComplete": "所有任务已完成",
"supervisor.todoList.title": "任务完成",
"tab.groupProfile": "群组档案",
- "tab.integration": "消息频道",
+ "tab.integration": "IM 机器人",
"tab.profile": "助理档案",
"tab.profileBasic": "基础档案",
"tab.search": "搜索",
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 12d9e72c68e..81cb793a939 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -20,7 +20,7 @@
"navigation.agents": "助手",
"navigation.appMenu": "应用菜单",
"navigation.apps": "应用",
- "navigation.channels": "消息频道",
+ "navigation.channels": "IM 机器人",
"navigation.chat": "对话",
"navigation.dashboard": "看板",
"navigation.discover": "发现",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index af0e9c4aa70..15fa71238b8 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -3269,8 +3269,8 @@
"workspace.onboarding.flow.assistant.hint": "💡 这是全队共用的助手,成员在对话和群聊里都能 @ 它",
"workspace.onboarding.flow.channels.connect.attempt": "第 {{count}} 次尝试",
"workspace.onboarding.flow.channels.connect.back": "返回列表",
- "workspace.onboarding.flow.channels.connect.category": "Bot 渠道",
- "workspace.onboarding.flow.channels.connect.connectedDesc": "群里的成员 @{{name}} 就能派活。之后可以在「Agent → 渠道」里修改。",
+ "workspace.onboarding.flow.channels.connect.category": "IM 机器人",
+ "workspace.onboarding.flow.channels.connect.connectedDesc": "群里的成员 @{{name}} 就能派活。之后可以在「Agent → IM 机器人」里修改。",
"workspace.onboarding.flow.channels.connect.connectedTitle": "{{name}} 已连接",
"workspace.onboarding.flow.channels.connect.description": "使用你们自己的 {{platform}} 应用,把 {{name}} 部署为团队群里的 Bot。",
"workspace.onboarding.flow.channels.connect.edit": "修改凭证",
@@ -3290,10 +3290,10 @@
"workspace.onboarding.flow.channels.connect.verifying": "正在调用平台 API 校验凭证…",
"workspace.onboarding.flow.channels.description": "给 {{name}} 接入一个团队自己的机器人,群里的成员 @{{name}} 就能派活,不需要每人单独绑定。",
"workspace.onboarding.flow.channels.highlight": "大家 @ 我就能派活。",
- "workspace.onboarding.flow.channels.more": "之后可以随时在「Agent → 渠道」里修改。",
+ "workspace.onboarding.flow.channels.more": "之后可以随时在「Agent → IM 机器人」里修改。",
"workspace.onboarding.flow.channels.quote": "把我接进团队的群聊,",
"workspace.onboarding.flow.channels.showLess": "收起",
- "workspace.onboarding.flow.channels.showMore": "更多渠道({{count}})",
+ "workspace.onboarding.flow.channels.showMore": "更多 IM 机器人({{count}})",
"workspace.onboarding.flow.channels.title": "把助手接入团队的聊天群",
"workspace.onboarding.flow.connectApps.apps.confluence": "浏览团队空间的文档,了解你们的项目、流程与决策",
"workspace.onboarding.flow.connectApps.apps.github": "分析团队的代码仓库与协作,了解你们的技术栈和分工",
diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.ts
index c1de4c8f7c6..cc012358d3a 100644
--- a/packages/locales/src/default/agent.ts
+++ b/packages/locales/src/default/agent.ts
@@ -1,5 +1,8 @@
export default {
'channel.quickSetup.needsApplicationId': 'Fill in the Application ID to get this link.',
+ 'channel.quickSetup.connect.title': 'Save and connect',
+ 'channel.quickSetup.connect.desc':
+ 'Saves what you filled in above and brings the bot online. Everything else can be changed later.',
'channel.quickSetup.link.createSlackApp': 'Create Slack app',
'channel.quickSetup.link.inviteBot': 'Invite bot to server',
'channel.quickSetup.link.openBotFather': 'Open BotFather',
@@ -12,9 +15,9 @@ export default {
'channel.quickSetup.scanToggle': 'Scan to create instead',
'channel.quickSetup.guideTitle': 'Setup steps',
'channel.quickSetup.feishu.scan.brandMismatch.lark':
- 'This app was created with a Lark account. Connect it from the Lark channel instead.',
+ 'This app was created with a Lark account. Connect it as a Lark bot instead.',
'channel.quickSetup.feishu.scan.brandMismatch.feishu':
- 'This app was created with a Feishu account. Connect it from the Feishu channel instead.',
+ 'This app was created with a Feishu account. Connect it as a Feishu bot instead.',
'channel.quickSetup.feishu.scan.regenerate': 'Generate a new code',
'channel.quickSetup.feishu.scan.title': 'Scan with Feishu to create the bot',
'channel.quickSetup.feishu.scan.does.app': 'Creates the app with the bot capability turned on',
@@ -106,25 +109,25 @@ export default {
'channel.connectionConfig': 'Connection Configuration',
'channel.copied': 'Copied to clipboard',
'channel.paidFeature.desc':
- '{{name}} is available on paid plans. Upgrade to any paid plan to configure and keep this channel connected.',
+ '{{name}} is available on paid plans. Upgrade to any paid plan to configure and keep this bot connected.',
'channel.paidFeature.title': 'Paid plan required',
'channel.paidFeature.badge': 'Pro',
'channel.paidFeature.cta.personal': 'Upgrade',
'channel.paidFeature.cta.workspace': 'Upgrade',
'channel.paidFeature.fieldLocked': 'Available on paid plans. Upgrade to configure this feature.',
'channel.paidFeature.enforce.desc':
- '{{name}} is available on paid plans. Upgrade to a paid personal plan or a Pro / Business workspace to configure and keep this channel connected.',
+ '{{name}} is available on paid plans. Upgrade to a paid personal plan or a Pro / Business workspace to configure and keep this bot connected.',
'channel.paidFeature.enforce.desc.personal':
- '{{name}} is available on paid personal plans. Upgrade to configure and keep this channel connected.',
+ '{{name}} is available on paid personal plans. Upgrade to configure and keep this bot connected.',
'channel.paidFeature.enforce.desc.workspace':
- '{{name}} is available on Pro / Business workspaces. Upgrade this workspace to configure and keep this channel connected.',
+ '{{name}} is available on Pro / Business workspaces. Upgrade this workspace to configure and keep this bot connected.',
'channel.paidFeature.enforce.title': 'Paid plan required',
'channel.paidFeature.notice.desc':
- 'Due to the high communication costs for the {{name}} channel, we plan to make this channel a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this channel now requires a paid personal plan or a Pro / Business workspace.',
+ 'Due to the high communication costs for the {{name}} bot, we plan to make this bot a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this bot now requires a paid personal plan or a Pro / Business workspace.',
'channel.paidFeature.notice.desc.personal':
- 'Due to the high communication costs for the {{name}} channel, we plan to make this channel a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this channel requires a paid personal plan.',
+ 'Due to the high communication costs for the {{name}} bot, we plan to make this bot a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this bot requires a paid personal plan.',
'channel.paidFeature.notice.desc.workspace':
- 'Due to the high communication costs for the {{name}} channel, we plan to make this channel a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this channel requires upgrading this workspace to Pro or Business.',
+ 'Due to the high communication costs for the {{name}} bot, we plan to make this bot a paid feature soon. Existing connections remain available during the notice period, but creating or reconnecting this bot requires upgrading this workspace to Pro or Business.',
'channel.paidFeature.notice.title': '{{name}} will soon require a paid plan',
'channel.paidFeature.noticeBadge': 'Pro soon',
'channel.comingSoon': 'Coming Soon',
@@ -132,18 +135,18 @@ export default {
'We are working on bringing this integration to LobeHub. Stay tuned for updates.',
'channel.comingSoonTitle': '{{name}} integration is coming soon',
'channel.copy': 'Copy',
- 'channel.deleteAllChannels': 'Remove All Channels',
+ 'channel.deleteAllChannels': 'Remove All IM Bots',
'channel.deleteAllConfirmDesc':
- 'This action will permanently remove all message channels and their configurations for this agent. This cannot be undone.',
+ 'This action will permanently remove all bots and their configurations for this agent. This cannot be undone.',
'channel.deleteAllSuccess': 'All channels removed',
- 'channel.deleteAllFailed': 'Failed to remove all channels',
+ 'channel.deleteAllFailed': 'Failed to remove all bots',
'channel.deleteConfirmDesc':
- 'This action will permanently remove this message channel and its configuration. This cannot be undone.',
+ 'This action will permanently remove this bot and its configuration. This cannot be undone.',
'channel.devWebhookProxyUrl': 'HTTPS Tunnel URL',
'channel.devWebhookProxyUrlHint':
'Optional. HTTPS tunnel URL for forwarding webhook requests to local dev server.',
'channel.discard': 'Discard',
- 'channel.home.title': 'Chat with <avatar/>{{name}} on Your Favorite App',
+ 'channel.home.title': 'Chat with <avatar/>{{name}} on Your Favorite Chat App',
'channel.platform.default.description':
'Let people reach this agent from {{name}} without switching apps—ideal for anyone who wants help close at hand.',
'channel.platform.discord.description':
@@ -195,13 +198,13 @@ export default {
'channel.connectionError.invalid_credentials':
'The bot credentials are invalid. Check the application ID, secret, and access tokens.',
'channel.connectionError.missing_credentials':
- 'Required bot credentials are missing. Complete the channel configuration and try again.',
+ 'Required bot credentials are missing. Complete the bot configuration and try again.',
'channel.connectionError.permission_denied':
"The platform denied access. Check the bot's permissions and enabled capabilities.",
'channel.connectionError.rate_limited':
'The platform is rate limiting this bot. Wait a moment and try again.',
'channel.connectionError.session_expired':
- 'The bot session has expired. Save the channel again to reconnect it.',
+ 'The bot session has expired. Save the bot again to reconnect it.',
'channel.connectionError.upstream_unavailable':
'The platform service is temporarily unavailable. LobeHub will try again later.',
'channel.endpointUrl': 'Webhook URL',
@@ -210,11 +213,11 @@ export default {
'channel.feishu.description': 'Connect this agent to Feishu for private and group chats.',
'channel.feishu.webhookMigrationTitle': 'Consider migrating to WebSocket mode',
'channel.feishu.webhookMigrationDesc':
- 'WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket in Advanced Settings. No additional configuration is needed on the Feishu/Lark Open Platform.',
+ 'WebSocket mode provides real-time event delivery without needing a public callback URL. To migrate, switch the Connection Mode to WebSocket under Connection options on the Connect tab. No additional configuration is needed on the Feishu/Lark Open Platform.',
'channel.imessage.description':
'Connect this agent to iMessage through the local LobeHub Desktop BlueBubbles bridge.',
'channel.imessage.applicationIdHint':
- 'A stable identifier shared by the cloud channel and the Desktop bridge.',
+ 'A stable identifier shared by the cloud bot and the Desktop bridge.',
'channel.imessage.applicationIdPlaceholder': 'e.g. home-mac-mini',
'channel.imessage.blueBubblesPassword': 'BlueBubbles Password',
'channel.imessage.blueBubblesPasswordHint':
@@ -296,7 +299,7 @@ export default {
'channel.qq.description': 'Connect this agent to QQ for group chats and direct messages.',
'channel.qq.webhookMigrationTitle': 'Consider migrating to WebSocket mode',
'channel.qq.webhookMigrationDesc':
- 'WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket in Advanced Settings.',
+ 'WebSocket mode provides real-time event delivery and automatic reconnection without needing a callback URL. To migrate, create a new bot on QQ Open Platform without configuring a callback URL, then switch the Connection Mode to WebSocket under Connection options on the Connect tab.',
'channel.wechat.description':
'Connect this agent to WeChat via iLink Bot for private and group chats.',
'channel.wechatQrExpired': 'QR code expired. Please refresh to get a new one.',
@@ -316,9 +319,9 @@ export default {
'channel.wechatUserId': 'WeChat User ID',
'channel.wechatBotIdHint': 'Bot identifier assigned after QR code authorization.',
'channel.wechatUserIdHint': 'WeChat account identifier returned by the authorization flow.',
- 'channel.removeChannel': 'Remove Channel',
- 'channel.removed': 'Channel removed',
- 'channel.removeFailed': 'Failed to remove channel',
+ 'channel.removeChannel': 'Remove IM Bot',
+ 'channel.removed': 'Bot removed',
+ 'channel.removeFailed': 'Failed to remove bot',
'channel.save': 'Save Configuration',
'channel.setupGuide': 'Setup Guide',
'channel.saveFailed': 'Failed to save configuration',
@@ -339,7 +342,7 @@ export default {
'Connect this agent to Slack for channel conversations and direct messages.',
'channel.slack.webhookMigrationTitle': 'Consider migrating to Socket Mode (WebSocket)',
'channel.slack.webhookMigrationDesc':
- 'Socket Mode provides real-time event delivery via WebSocket without exposing a public HTTP endpoint. To migrate, enable Socket Mode in your Slack app settings, generate an App-Level Token, then switch the Connection Mode to WebSocket in Advanced Settings.',
+ 'Socket Mode provides real-time event delivery via WebSocket without exposing a public HTTP endpoint. To migrate, enable Socket Mode in your Slack app settings, generate an App-Level Token, then switch the Connection Mode to WebSocket under Connection options on the Connect tab.',
'channel.secretTokenHint':
'Used to verify webhook requests from Telegram. Leave blank and LobeHub derives one for this bot — verification is always on.',
'channel.secretTokenPlaceholder': 'Leave blank to auto-generate',
@@ -508,7 +511,89 @@ export default {
'channel.botWakeCooldownSeconds': 'Cool down (seconds)',
'channel.botWakeCooldownSecondsHint':
'Quiet time after a run before the next one may start. At least 60.',
+ 'channel.group.setup': 'Get started',
+ 'channel.group.credentialsDesc': 'Encrypted when saved, and shown masked afterwards.',
+ 'channel.group.credentialsOptional': 'Optional credentials',
+ 'channel.quickView.title': 'Quick view',
+ 'channel.quickView.open': 'Preview',
+ 'channel.quickView.collapse': 'Collapse preview',
+ 'channel.quickView.desc':
+ 'How the bot behaves in chat with the settings as they are now, before you save. Illustrative.',
+ 'channel.quickView.sceneGroup': 'Group',
+ 'channel.quickView.sceneDm': 'Direct message',
+ 'channel.quickView.stranger': 'Someone new',
+ 'channel.quickView.bot': 'Bot',
+ 'channel.quickView.ask': "Summarize today's discussion",
+ 'channel.quickView.askDm': "Can you summarize today's discussion?",
+ 'channel.quickView.answer':
+ 'Three things came up today: the release moved to Thursday, the sign-in page copy, and the priority of the bug list. Want me to turn them into to-dos?',
+ 'channel.quickView.toolCall': 'Read 12 earlier messages',
+ 'channel.quickView.dm.pairing':
+ "To DM this bot, send this pairing code to the bot's owner: 7K2F. They run /approve 7K2F to grant you access. The code expires in 1 hour.",
+ 'channel.quickView.dm.allowlist':
+ "Sorry, you aren't authorized to send direct messages to this bot. Please contact the bot's owner if you need access.",
+ 'channel.quickView.dm.disabled':
+ "This bot isn't accepting direct messages. Please reach out by mentioning it in a shared channel or group instead.",
+ 'channel.quickView.group.disabled':
+ "This bot doesn't respond in groups or channels. Please reach out via direct message instead.",
+ 'channel.quickView.group.allowlist':
+ "This bot isn't enabled in this channel. Please contact the bot's owner if you need access.",
+ 'channel.quickView.sender.rejected':
+ "Sorry, you aren't authorized to interact with this bot. Please contact the bot's owner if you need access.",
+ 'channel.quickView.groupAllowlist': 'Replies only in the groups on your list.',
+ 'channel.quickView.keywords': 'Also wakes on {{keywords}} without an @mention.',
+ 'channel.saveAndConnect': 'Save and connect',
+ 'channel.access.recommended': 'Recommended',
+ 'channel.access.dm.label': 'Who can message it directly',
+ 'channel.access.dm.everyone': 'Everyone',
+ 'channel.access.dm.everyoneDesc': 'Anyone can message it directly.',
+ 'channel.access.dm.approval': 'Strangers need my approval',
+ 'channel.access.dm.approvalDesc':
+ 'A stranger gets a pairing code, and you run /approve to let them in.',
+ 'channel.access.dm.listed': 'Only people on the list',
+ 'channel.access.dm.listedDesc': 'Only listed people can use it; everyone else is turned away.',
+ 'channel.access.dm.closed': 'No direct messages',
+ 'channel.access.dm.closedDesc': 'It ignores DMs and points people to a shared group instead.',
+ 'channel.access.list.approved': 'Approved people',
+ 'channel.access.list.listed': 'People on the list',
+ 'channel.access.list.hint':
+ 'The list applies everywhere: only these people can use the bot, in DMs and in groups.',
+ 'channel.access.list.emptyApproval': 'No one is approved yet. Strangers get a pairing code.',
+ 'channel.access.list.emptyListed':
+ 'The list is empty, so apart from you nobody can message it yet.',
+ 'channel.access.list.clearTitle': 'Clear the list?',
+ 'channel.access.list.clearContent':
+ 'Switching to Everyone also removes the {{count}} people on the list, since a filled list limits everyone.',
+ 'channel.access.list.clearOk': 'Switch and clear',
+ 'channel.access.group.label': 'How it responds in groups and channels',
+ 'channel.access.group.open': 'Every group and channel',
+ 'channel.access.group.openDesc': 'Replies whenever it is @mentioned.',
+ 'channel.access.group.allowlist': 'Only chosen groups',
+ 'channel.access.group.allowlistDesc': 'Replies only in the groups you list below.',
+ 'channel.access.group.disabled': 'Not in groups',
+ 'channel.access.group.disabledDesc': 'It ignores group messages and points people to a DM.',
+ 'channel.access.group.listNote':
+ 'The people list above also applies here: only people on it can use the bot in groups.',
+ 'channel.access.identity.desc':
+ 'Lets the bot reach you with reminders and notices, and makes you the one who approves strangers. The settings below never block you.',
+ 'channel.access.identity.required': 'Required to approve strangers',
+ 'channel.access.identity.approverMissing':
+ 'To approve strangers, add your own ID first, or nobody can run /approve.',
+ 'channel.hero.title': '{{name}} bot',
+ 'channel.hero.connected': '{{agent}} · app ID {{id}}',
+ 'channel.hero.new': 'Once connected, {{agent}} can work in {{name}}.',
+ 'channel.tab.connect': 'Connect',
+ 'channel.tab.access': 'Access',
+ 'channel.tab.reply': 'Replies',
+ 'channel.tab.wake': 'Wake policy',
+ 'channel.wake.intro':
+ 'Decides whether the bot may answer a message nobody addressed to it: a watch keyword in a thread it was not mentioned in, or a message continuing a conversation it already joined. Plain channel chatter is only judged and recorded, never answered.',
+ 'channel.tab.advanced': 'Advanced',
+ 'channel.group.connection': 'Connection options',
+ 'channel.reply.instant':
+ 'Changes here take effect as soon as you make them. There is nothing to save.',
'channel.settings': 'Advanced Settings',
+ 'channel.settingsResetConfirm': 'Are you sure you want to reset advanced settings to default?',
'channel.settingsResetDefault': 'Reset to Default',
'channel.signingSecret': 'Signing Secret',
'channel.signingSecretHint': 'Used to verify webhook requests.',
@@ -529,7 +614,8 @@ export default {
'channel.historyLimit': 'History Message Limit',
'channel.historyLimitHint': 'Default number of messages to fetch when reading channel history',
'channel.serverId': 'Default Server ID',
- 'channel.serverIdHint': 'Default server / guild AI tools act on; not used for access control',
+ 'channel.serverIdHint':
+ 'When the bot uses its tools (looking up channels, reading or sending messages) without being told which server, it works in this one. It does not decide where the bot replies.',
'channel.serverIdHint.discord':
'Enable Developer Mode (Settings → Advanced), then right-click the server icon → Copy Server ID.',
'channel.serverIdHint.slack':
@@ -537,6 +623,8 @@ export default {
'channel.userId': 'Your Platform User ID',
'channel.userIdHint':
'Lets AI tools reach you proactively (e.g. reminders); auto-trusted by the global allowlist',
+ 'channel.userIdMissingDesc':
+ "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in on the Access tab.",
'channel.userIdMissingTitle': 'Add your platform User ID',
'channel.userIdHint.discord':
'Enable Developer Mode (Settings → Advanced), then right-click your avatar → Copy User ID.',
@@ -806,7 +894,7 @@ export default {
'transfer.confirm.warning': "Some links won't move:",
'transfer.confirm.plugins': 'Custom plugins may not be available in the target workspace',
'transfer.confirm.chatGroups': 'Multi-agent group associations will be removed',
- 'transfer.confirm.botChannels': 'Bot channel connections may need to be refreshed after moving',
+ 'transfer.confirm.botChannels': 'Bot connections may need to be refreshed after moving',
'transfer.success': 'Agent moved successfully',
'transfer.transferTo': 'Move to…',
'transfer.transferToMember': 'Transfer to member...',
@@ -940,35 +1028,4 @@ export default {
'share.settings.profile.unsaved':
'You have unsaved changes. Visitors will only see them after you save.',
'share.settings.profile.upToDate': 'Visitors see the saved content.',
- 'channel.quickSetup.guideDesc':
- 'Create the bot in {{name}}, then paste its credentials under Connection.',
- 'channel.detailDesc':
- 'Connect a {{name}} bot so {{agent}} can receive and reply to messages in {{name}}.',
- 'channel.detailDescAgentFallback': 'this agent',
- 'channel.section.connection.title': 'Connection',
- 'channel.section.connection.desc': 'Credentials the bot uses to sign in to {{name}}.',
- 'channel.section.access.title': 'Access',
- 'channel.section.access.desc': 'Who can talk to the bot, and where it responds.',
- 'channel.section.account.title': 'Your account',
- 'channel.section.account.desc':
- 'Which {{name}} account is yours. The agent uses it to reach you and to approve pairing requests.',
- 'channel.section.replies.title': 'Replies',
- 'channel.section.replies.desc':
- 'How the bot handles messages that arrive together, and what its replies include.',
- 'channel.section.wake.title': 'Wake-up',
- 'channel.section.wake.desc': 'When the bot steps in without an @mention.',
- 'channel.section.other.title': 'Other',
- 'channel.section.danger.title': 'Danger zone',
- 'channel.dangerZone.resetDesc':
- 'Restore every setting except the credentials to its default. Takes effect after you save.',
- 'channel.dangerZone.removeDesc':
- "Delete this channel's credentials and settings, and disconnect the bot from {{name}}. This cannot be undone.",
- 'channel.dangerZone.resetConfirm':
- 'Reset every setting except the credentials to its default? Takes effect after you save.',
- 'channel.saveBar.unsaved': 'You have unsaved changes',
- 'channel.saveBar.firstSave': 'The bot connects as soon as you save.',
- 'channel.saveAndConnect': 'Save and Connect',
- 'channel.userIdMissingAction': 'Add User ID',
- 'channel.userIdMissingHint':
- "Without it, AI tools can't reach you with reminders, and pairing approvals will fail. Send /whoami to the bot to get your ID, then fill it in under Your account.",
} as const;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index f88f48525a9..61c04c5c209 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -1898,7 +1898,7 @@ export default {
'supervisor.todoList.allComplete': 'All tasks completed',
'supervisor.todoList.title': 'Tasks Completed',
'tab.groupProfile': 'Group Profile',
- 'tab.integration': 'Channels',
+ 'tab.integration': 'IM Bots',
'tab.profile': 'Agent Profile',
'tab.profileBasic': 'Profile',
'tab.search': 'Search',
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 9919822ca21..642f7beea7f 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -12,7 +12,7 @@ export default {
'navigation.agentShare': 'Share',
'navigation.agents': 'Agents',
- 'navigation.channels': 'Channels',
+ 'navigation.channels': 'IM Bots',
'navigation.chat': 'Chat',
'navigation.dashboard': 'Dashboards',
'navigation.discover': 'Discover',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 8e260223c65..8633dad618b 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -3647,11 +3647,11 @@ When I am ___, I need ___
'Connect a bot your team owns to {{name}}. Everyone in the group can @{{name}} to hand off work — nobody has to link an account.',
'workspace.onboarding.flow.channels.quote': "Add me to your team's group chats,",
'workspace.onboarding.flow.channels.highlight': 'and anyone can hand me work.',
- 'workspace.onboarding.flow.channels.showMore': 'More channels ({{count}})',
+ 'workspace.onboarding.flow.channels.showMore': 'More IM bots ({{count}})',
'workspace.onboarding.flow.channels.showLess': 'Show less',
- 'workspace.onboarding.flow.channels.more': 'You can change channels anytime in Agent → Channels.',
+ 'workspace.onboarding.flow.channels.more': 'You can change IM bots anytime in Agent → IM Bots.',
'workspace.onboarding.flow.channels.connect.back': 'Back to list',
- 'workspace.onboarding.flow.channels.connect.category': 'Bot channel',
+ 'workspace.onboarding.flow.channels.connect.category': 'IM Bot',
'workspace.onboarding.flow.channels.connect.description':
"Use your own {{platform}} app to bring {{name}} into your team's chats as a bot.",
'workspace.onboarding.flow.channels.connect.guide': 'Setup guide',
@@ -3668,7 +3668,7 @@ When I am ___, I need ___
'workspace.onboarding.flow.channels.connect.attempt': 'Attempt {{count}}',
'workspace.onboarding.flow.channels.connect.connectedTitle': '{{name}} connected',
'workspace.onboarding.flow.channels.connect.connectedDesc':
- 'Members can now @{{name}} in your group to hand off work. Change it anytime in Agent → Channels.',
+ 'Members can now @{{name}} in your group to hand off work. Change it anytime in Agent → IM Bots.',
'workspace.onboarding.flow.channels.connect.edit': 'Edit credentials',
'workspace.onboarding.flow.channels.connect.failedTitle': "Couldn't connect {{name}}",
'workspace.onboarding.flow.channels.connect.errorCode': 'Error code: {{code}}',
diff --git a/scripts/stylexMigration/legacyFiles.json b/scripts/stylexMigration/legacyFiles.json
index 4659728c419..648c1f0d0df 100644
--- a/scripts/stylexMigration/legacyFiles.json
+++ b/scripts/stylexMigration/legacyFiles.json
@@ -390,7 +390,6 @@
"src/features/AgentChannel/platform/wechat/ConnectedInfo.tsx",
"src/features/AgentChannel/platform/wechat/QrCodeAuth.tsx",
"src/features/AgentChannel/quickSetup/FeishuQuickCreate.tsx",
- "src/features/AgentChannel/quickSetup/SetupGuide.tsx",
"src/features/AgentDocumentPage/RightPanel/index.tsx",
"src/features/AgentDocumentReader/index.tsx",
"src/features/AgentDocumentsExplorer/DocumentExplorerToolbar.tsx",
diff --git a/src/features/AgentChannel/PlatformDetail/AccessSection.tsx b/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
new file mode 100644
index 00000000000..8b63f34bb5f
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/AccessSection.tsx
@@ -0,0 +1,216 @@
+'use client';
+
+import { confirmModal, Text } from '@lobehub/ui';
+import { Form, type FormInstance, useWatch } from '@lobehub/ui/form';
+import { memo, type ReactNode, useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { FieldSchema } from '@/server/services/bot/platforms/types';
+
+import {
+ type AccessSettings,
+ applyDmStance,
+ countListed,
+ deriveDmStance,
+ type DmStance,
+ dropHiddenIncompleteRows,
+} from './accessStance';
+import { ChoiceList, type ChoiceOption } from './ChoiceList';
+import type { ChannelFormValues } from './index';
+import { SchemaField } from './SchemaField';
+
+type GroupPolicy = 'allowlist' | 'disabled' | 'open';
+
+interface AccessSectionProps {
+ disabled?: boolean;
+ /** The access fields the platform declares; only ones present are shown. */
+ fields: FieldSchema[];
+ form: FormInstance<ChannelFormValues>;
+ onValuesChange?: (values: ChannelFormValues) => void;
+ /** Platform helper rendered right under the owner ID field (e.g. Feishu's lookup). */
+ userIdExtras?: ReactNode;
+}
+
+/**
+ * "Who can use it", asked as decisions instead of settings.
+ *
+ * The runtime decides access with `dmPolicy`, a global people list (`allowFrom`),
+ * a group policy and a group list. This section lets a person choose one
+ * stance per surface and only then shows what that choice needs: the list for
+ * "approval" and "listed", the owner's ID for approving. The list stays mounted
+ * when hidden so a saved list is never dropped by a save.
+ */
+export const AccessSection = memo<AccessSectionProps>(
+ ({ disabled, fields, form, onValuesChange, userIdExtras }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string, options?: Record<string, unknown>) => string;
+
+ const byKey = useMemo(() => new Map(fields.map((field) => [field.key, field])), [fields]);
+ const watched = useWatch(form, (values) => values.settings);
+ const settings = useMemo(() => (watched ?? {}) as AccessSettings, [watched]);
+
+ const stance = deriveDmStance(settings);
+ const groupPolicy = (settings.groupPolicy as GroupPolicy | undefined) ?? 'open';
+ const hasPeopleList = countListed(settings.allowFrom) > 0;
+
+ const write = useCallback(
+ (patch: Record<string, unknown>) => {
+ const current = (form.getValues().settings ?? {}) as Record<string, unknown>;
+ const next = { ...current, ...patch };
+ // A list this choice hides must not keep a half-added row: its hidden
+ // "ID required" error would block every save.
+ Object.assign(next, dropHiddenIncompleteRows(next));
+ form.setValues({ settings: next as Record<string, {} | undefined> });
+ onValuesChange?.(form.getValues());
+ },
+ [form, onValuesChange],
+ );
+
+ const handleStance = useCallback(
+ (next: DmStance) => {
+ if (next === stance) return;
+ const { dropped, patch } = applyDmStance(next, settings);
+
+ // Switching to "everyone" has to empty the list, or the list would keep
+ // restricting everyone. Say so before throwing people off it.
+ if (dropped > 0) {
+ confirmModal({
+ content: t('channel.access.list.clearContent', { count: dropped }),
+ okText: t('channel.access.list.clearOk'),
+ onOk: () => write(patch),
+ title: t('channel.access.list.clearTitle'),
+ });
+ return;
+ }
+
+ write(patch);
+ },
+ [settings, stance, t, write],
+ );
+
+ // Each option states what it does, so the choice is made by reading the
+ // options rather than by opening one.
+ const dmOptions: ChoiceOption<DmStance>[] = (
+ ['everyone', 'approval', 'listed', 'closed'] as const
+ ).map((value) => ({
+ desc: t(`channel.access.dm.${value}Desc`),
+ label: t(`channel.access.dm.${value}`),
+ recommendedLabel: value === 'approval' ? t('channel.access.recommended') : undefined,
+ value,
+ }));
+ const groupOptions: ChoiceOption<GroupPolicy>[] = (
+ ['open', 'allowlist', 'disabled'] as const
+ ).map((value) => ({
+ desc: t(`channel.access.group.${value}Desc`),
+ label: t(`channel.access.group.${value}`),
+ value,
+ }));
+
+ const userId = byKey.get('userId');
+ const serverId = byKey.get('serverId');
+ const allowFrom = byKey.get('allowFrom');
+ const guestPolicy = byKey.get('guestPolicy');
+ const groupAllowFrom = byKey.get('groupAllowFrom');
+
+ const approverMissing =
+ settings.dmPolicy === 'pairing' &&
+ !(typeof settings.userId === 'string' && settings.userId.trim());
+ // A filled list limits everyone in every surface, so it stays visible (and
+ // clearable) whatever the DM stance is.
+ const listVisible = stance === 'approval' || stance === 'listed' || hasPeopleList;
+
+ return (
+ <>
+ {userId && (
+ <SchemaField
+ disabled={disabled}
+ field={userId}
+ parentKey="settings"
+ descOverride={
+ <>
+ {t('channel.access.identity.desc')}
+ {approverMissing && (
+ <Text fontSize={12} style={{ display: 'block' }} type={'warning'}>
+ {t('channel.access.identity.approverMissing')}
+ </Text>
+ )}
+ </>
+ }
+ validateOverride={() =>
+ form.getValue('settings.dmPolicy') === 'pairing' &&
+ !String(form.getValue('settings.userId') ?? '').trim()
+ ? t('channel.access.identity.required')
+ : undefined
+ }
+ />
+ )}
+ {userIdExtras}
+ {/* Your server sits with your own ID: both say what is yours, not who may talk. */}
+ {serverId && (
+ <SchemaField divider disabled={disabled} field={serverId} parentKey="settings" />
+ )}
+
+ {byKey.has('dmPolicy') && (
+ <Form.Field divider label={t('channel.access.dm.label')} layout="vertical">
+ <ChoiceList
+ aria-label={t('channel.access.dm.label')}
+ disabled={disabled}
+ options={dmOptions}
+ value={stance}
+ onChange={handleStance}
+ />
+ </Form.Field>
+ )}
+ {allowFrom && (
+ <SchemaField
+ divider
+ descOverride={t('channel.access.list.hint')}
+ disabled={disabled}
+ field={allowFrom}
+ hidden={!listVisible}
+ parentKey="settings"
+ emptyOverride={t(
+ stance === 'approval'
+ ? 'channel.access.list.emptyApproval'
+ : 'channel.access.list.emptyListed',
+ )}
+ labelOverride={t(
+ stance === 'approval' ? 'channel.access.list.approved' : 'channel.access.list.listed',
+ )}
+ />
+ )}
+ {guestPolicy && (
+ <SchemaField divider disabled={disabled} field={guestPolicy} parentKey="settings" />
+ )}
+
+ {byKey.has('groupPolicy') && (
+ <Form.Field
+ divider
+ desc={hasPeopleList ? t('channel.access.group.listNote') : undefined}
+ label={t('channel.access.group.label')}
+ layout="vertical"
+ >
+ <ChoiceList
+ aria-label={t('channel.access.group.label')}
+ disabled={disabled}
+ options={groupOptions}
+ value={groupPolicy}
+ onChange={(next) => write({ groupPolicy: next })}
+ />
+ </Form.Field>
+ )}
+ {groupAllowFrom && (
+ <SchemaField
+ divider
+ disabled={disabled}
+ field={{ ...groupAllowFrom, visibleWhen: undefined }}
+ hidden={groupPolicy !== 'allowlist'}
+ parentKey="settings"
+ />
+ )}
+ </>
+ );
+ },
+);
+
+AccessSection.displayName = 'ChannelAccessSection';
diff --git a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
index 9c2444fcd85..59e8e1379db 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.botWake.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import { useForm } from '@lobehub/ui/form';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { render, screen } from '@testing-library/react';
import { useEffect } from 'react';
import { describe, expect, it, vi } from 'vitest';
@@ -12,7 +12,12 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platfor
import agentZh from '../../../../locales/zh-CN/agent.json';
import agentEn from '../../../../packages/locales/src/default/agent';
import Body from './Body';
-import { getChannelFormValues, mergeSettingsWithDefaults } from './formState';
+import {
+ getChannelFormValues,
+ isWakeMasterReleased,
+ mergeSettingsWithDefaults,
+ withWakeMasterOn,
+} from './formState';
import type { ChannelFormValues } from './index';
const state = vi.hoisted(() => ({
@@ -58,7 +63,11 @@ const platformDef = {
/** Mounts the form the way the channel page does: a saved bot, its settings merged with the defaults. */
const Harness = ({ settings }: { settings?: Record<string, unknown> }) => {
const form = useForm<ChannelFormValues>();
- const saved = mergeSettingsWithDefaults(discordSchema, settings ?? {});
+ // The page switches the master on for a user the options are released to.
+ const saved = withWakeMasterOn(
+ mergeSettingsWithDefaults(discordSchema, settings ?? {}),
+ isWakeMasterReleased(discordSchema, state.featureFlags),
+ );
useEffect(() => {
form.setValues(
@@ -70,6 +79,7 @@ const Harness = ({ settings }: { settings?: Record<string, unknown> }) => {
return (
<Body
hasConfig
+ activeTab="wake"
currentConfig={{ applicationId: '1', credentials: {}, settings: saved }}
form={form}
platformDef={platformDef}
@@ -90,8 +100,8 @@ describe('channel settings form: bot-wake options', () => {
// The form is up (an ordinary advanced setting renders) ...
expect(screen.getByText(en['channel.watchKeywords'])).toBeInTheDocument();
// ... and no bot-wake option leaks out.
- expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
expect(screen.queryByText(en['channel.botWakeMode'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.wake.intro'])).not.toBeInTheDocument();
});
it('also hides them while the flags are explicitly off', () => {
@@ -100,25 +110,17 @@ describe('channel settings form: bot-wake options', () => {
render(<Harness />);
- expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
+ expect(screen.queryByText(en['channel.botWakeMode'])).not.toBeInTheDocument();
});
- it('shows only the master switch once released, and the rest after it is turned on', async () => {
+ it('has no master switch: the rules show straight away once released, the timings after batching is on', () => {
state.copy = en;
state.featureFlags = { enableBotWake: true };
render(<Harness />);
- expect(screen.getByText(en['channel.botWakeEnabled'])).toBeInTheDocument();
- expect(screen.queryByText(en['channel.botWakeMode'])).not.toBeInTheDocument();
- expect(screen.queryByText(en['channel.botWakeClassifierMode'])).not.toBeInTheDocument();
- expect(screen.queryByText(en['channel.botWakeSchedulerMode'])).not.toBeInTheDocument();
-
- fireEvent.click(
- screen.getByRole('switch', { name: new RegExp(`^${en['channel.botWakeEnabled']}`) }),
- );
-
- await waitFor(() => expect(screen.getByText(en['channel.botWakeMode'])).toBeInTheDocument());
+ expect(screen.queryByText(en['channel.botWakeEnabled'])).not.toBeInTheDocument();
+ expect(screen.getByText(en['channel.botWakeMode'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeScope'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeAllowChannels'])).toBeInTheDocument();
expect(screen.getByText(en['channel.botWakeClassifierMode'])).toBeInTheDocument();
@@ -128,6 +130,15 @@ describe('channel settings form: bot-wake options', () => {
expect(screen.queryByText(en['channel.botWakeCollectSeconds'])).not.toBeInTheDocument();
});
+ it('explains what the options do, since there is no switch to read', () => {
+ state.copy = en;
+ state.featureFlags = { enableBotWake: true };
+
+ render(<Harness />);
+
+ expect(screen.getByText(en['channel.wake.intro'])).toBeInTheDocument();
+ });
+
it('opens straight onto the options for a bot that already has them on', () => {
state.copy = en;
state.featureFlags = { enableBotWake: true };
@@ -145,7 +156,6 @@ describe('channel settings form: bot-wake options', () => {
render(<Harness settings={{ botWakeEnabled: true }} />);
- expect(screen.getByText('按规则判断未定向消息')).toBeInTheDocument();
expect(screen.getByText('跟进窗口(秒)')).toBeInTheDocument();
expect(screen.getByText('自定义说明')).toBeInTheDocument();
expect(screen.queryByText('channel.botWakeMode')).not.toBeInTheDocument();
diff --git a/src/features/AgentChannel/PlatformDetail/Body.tsx b/src/features/AgentChannel/PlatformDetail/Body.tsx
index 563d2a71a61..7220805f320 100644
--- a/src/features/AgentChannel/PlatformDetail/Body.tsx
+++ b/src/features/AgentChannel/PlatformDetail/Body.tsx
@@ -1,8 +1,8 @@
'use client';
-import { Button, confirmModal } from '@lobehub/ui';
+import { Button, confirmModal, Flexbox, Text } from '@lobehub/ui';
import { Form, type FormInstance } from '@lobehub/ui/form';
-import { RotateCcw, Trash2 } from 'lucide-react';
+import { RotateCcw } from 'lucide-react';
import { Fragment, memo, type ReactNode, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -17,26 +17,39 @@ import {
platformCredentialExtrasMap,
platformSettingsFieldExtrasMap,
} from '../platform/registry';
+import { getInlineFieldKeys } from '../quickSetup/guides';
import QuickSetupSection from '../quickSetup/QuickSetupSection';
-import { extractSettingsDefaults } from './formState';
+import { AccessSection } from './AccessSection';
+import type { ChannelTab } from './channelTabs';
+import { extractSettingsDefaults, WAKE_MASTER_KEY } from './formState';
import type { ChannelFormValues } from './index';
-import { ApplicationIdField, getFields, SchemaField } from './SchemaField';
-import { groupSettingsFields, type SettingsSectionKey } from './sections';
-import { ACCOUNT_SECTION_ID } from './StatusAlerts';
-import WebhookUrlField from './WebhookUrlField';
+import { ApplicationIdField, SchemaField } from './SchemaField';
+import { getSchemaFields, groupSettingsFields, WAKE_KEY_PREFIX } from './settingsGroups';
-export { buildValidate } from './SchemaField';
-
-/** DOM anchors for sections other parts of the page link to. */
-const SECTION_ANCHORS: Partial<Record<SettingsSectionKey, string>> = {
- account: ACCOUNT_SECTION_ID,
-};
+/**
+ * One tab's content. Every panel stays mounted and only the active one is
+ * visible, so a field on another tab keeps its value and is still validated
+ * and saved with the form.
+ */
+const Panel = ({
+ active,
+ children,
+ tab,
+}: {
+ active: boolean;
+ children: ReactNode;
+ tab: ChannelTab;
+}) => (
+ <div hidden={!active} id={`channel-panel-${tab}`} role="tabpanel">
+ <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>{children}</div>
+ </div>
+);
// --------------- Body component ---------------
interface BodyProps {
- /** Rendered at the right of the Connection heading (e.g. Test Connection). */
- connectionExtra?: ReactNode;
+ /** The tab shown; the others stay mounted but hidden. */
+ activeTab: ChannelTab;
currentConfig?: {
applicationId: string;
credentials: Record<string, string>;
@@ -50,243 +63,312 @@ interface BodyProps {
applicationId: string;
credentials: Record<string, string>;
}) => Promise<boolean> | void;
- /** Removes the saved channel; the Danger zone offers it only for a saved bot. */
- onDelete?: () => void;
+ /** Saves and connects the bot; offered as a step of its own while setting one up. */
+ onSave?: () => void;
onValuesChange?: (values: ChannelFormValues) => void;
platformDef: SerializedPlatformDefinition;
/** Name a quick-created bot app starts with (the agent's name). */
quickSetupAppName?: string;
/** Who a quick-created bot app is for (the agent id); a new scope starts a new scan. */
quickSetupScope?: string;
- /** Removing is unavailable (read-only, or a save / connect is in flight). */
- removeDisabled?: boolean;
+ /** A save is running. */
+ saving?: boolean;
}
-/**
- * A channel's configuration as settings sections: how the bot connects, who may
- * talk to it, which platform account is the operator's, how it replies and when
- * it wakes up, then the destructive actions. Until the bot is first saved the
- * settings sections start folded, so the page leads with the credentials.
- */
const Body = memo<BodyProps>(
({
- connectionExtra,
+ activeTab,
platformDef,
form,
hasConfig,
currentConfig,
onAuthenticated,
- onDelete,
+ onSave,
onValuesChange,
disabled,
quickSetupAppName,
+ saving,
quickSetupScope,
- removeDisabled,
}) => {
const { t: _t } = useTranslation('agent');
- const t = _t as (key: string, options?: Record<string, unknown>) => string;
+ const t = _t as (key: string) => string;
const CustomCredentialBody = platformCredentialBodyMap[platformDef.id];
const CredentialExtras = platformCredentialExtrasMap[platformDef.id];
+ // Fields behind a rollout flag stay hidden until the user's flag is on (and
+ // while the flags have not loaded yet).
const featureFlags = useServerConfigStore((s) => s.featureFlags) as
Record<string, unknown> | undefined;
const credentialFields = useMemo(
- () => getFields(platformDef.schema, 'credentials', featureFlags),
+ () => getSchemaFields(platformDef.schema, 'credentials', featureFlags),
[platformDef.schema, featureFlags],
);
- const settingsFields = useMemo(
- () => getFields(platformDef.schema, 'settings', featureFlags),
+ const settingsGroups = useMemo(
+ () => groupSettingsFields(getSchemaFields(platformDef.schema, 'settings', featureFlags)),
[platformDef.schema, featureFlags],
);
- const { connection: connectionSettings, sections } = useMemo(
- () => groupSettingsFields(settingsFields),
- [settingsFields],
+ // While a bot is being set up, its credentials are asked for in the setup
+ // step that produces them. A saved bot has no steps on screen, so they sit
+ // in the credentials group.
+ const inlineKeys = useMemo(
+ () => (hasConfig ? new Set<string>() : getInlineFieldKeys(platformDef.id)),
+ [hasConfig, platformDef.id],
);
- const handleResetSettings = useCallback(() => {
- form.setValues({
- settings: extractSettingsDefaults(platformDef.schema) as Record<string, {} | undefined>,
- });
- onValuesChange?.(form.getValues());
- }, [form, onValuesChange, platformDef.schema]);
+ const renderStepField = (key: string) => {
+ if (key === 'applicationId') {
+ const field = platformDef.schema.find((section) => section.key === 'applicationId');
+ return field && <ApplicationIdField disabled={disabled} field={field} />;
+ }
+ if (key === 'extras') return CredentialExtras && <CredentialExtras disabled={disabled} />;
+ const field = credentialFields.find((item) => item.key === key);
+ return (
+ field && <SchemaField fullWidth disabled={disabled} field={field} parentKey="credentials" />
+ );
+ };
+
+ const groupCredentialFields = credentialFields.filter((field) => !inlineKeys.has(field.key));
+ const showExtras = !!CredentialExtras && !inlineKeys.has('extras');
+ const showApplicationId =
+ !inlineKeys.has('applicationId') &&
+ platformDef.schema.some((section) => section.key === 'applicationId');
+
+ const connectGroup = settingsGroups.find((group) => group.key === 'connect');
+
+ // Reset only what the section shows: access rules and reply style are
+ // deliberate choices, so a reset button on "Advanced" must not touch them.
+ const handleResetGroup = useCallback(
+ (fields: FieldSchema[]) => {
+ const defaults = extractSettingsDefaults(platformDef.schema);
+ const next = { ...form.getValues().settings };
+ for (const field of fields) next[field.key] = defaults[field.key] as {} | undefined;
+
+ form.setValues({ settings: next });
+ onValuesChange?.(form.getValues());
+ },
+ [form, onValuesChange, platformDef.schema],
+ );
// A settings-field helper writes straight into the form, which does not
- // fire the Form's `onValuesChange` — same reason `handleResetSettings`
+ // fire the Form's `onValuesChange` — same reason `handleResetGroup`
// reports its own write. Without this the page never sees the change and
// the unsaved-changes affordances stay hidden.
const handleFieldExtrasFilled = useCallback(() => {
onValuesChange?.(form.getValues());
}, [form, onValuesChange]);
- const renderSettingsField = (field: FieldSchema, index: number) => {
- // Feature-gated fields (e.g. watch keywords) lock when the resolved
- // access meta reports the feature as not allowed.
- const featureLocked =
- !!field.paidFeature && platformDef.access?.features?.[field.paidFeature]?.allowed === false;
+ // A platform's helper that sits under one setting (e.g. Feishu's "fetch my
+ // Open ID" under the owner ID).
+ const renderExtras = (field?: FieldSchema, featureLocked = false) => {
+ if (!field) return null;
const FieldExtras = platformSettingsFieldExtrasMap[`${platformDef.id}:${field.key}`];
+ if (!FieldExtras) return null;
+
return (
- <Fragment key={field.key}>
- <SchemaField
- disabled={disabled}
- divider={index > 0}
- featureLocked={featureLocked}
- field={field}
- parentKey="settings"
- />
- {FieldExtras && (
- <FieldExtras
- disabled={disabled || featureLocked}
- platformId={platformDef.id}
- savedValue={currentConfig?.settings?.[field.key]}
- onFilled={handleFieldExtrasFilled}
- />
- )}
- </Fragment>
+ <FieldExtras
+ disabled={disabled || featureLocked}
+ platformId={platformDef.id}
+ savedValue={currentConfig?.settings?.[field.key]}
+ onFilled={handleFieldExtrasFilled}
+ />
);
};
- // Render top-level sections in schema order so each platform controls its
- // own field ordering. LINE places `credentials` before `applicationId`
- // because the operator must enter the channel access token before the
- // "Fetch from LINE" button (rendered after applicationId) can auto-fill the
- // destination user ID; Discord/Slack/QQ/Feishu place `applicationId` first
- // as a primary identifier.
- const credentialRows = platformDef.schema
- .filter((section) => section.key === 'applicationId' || section.key === 'credentials')
- .flatMap((section) => {
- if (section.key === 'applicationId') return [{ field: section, key: 'applicationId' }];
- return credentialFields.map((field) => ({ field, key: field.key }));
- });
-
- const showReset = !!hasConfig && settingsFields.length > 0;
- const showRemove = hasConfig && !!onDelete;
-
return (
- <Form form={form} style={{ width: '100%' }} variant={'filled'}>
- {!CustomCredentialBody && (
- <QuickSetupSection
- appName={quickSetupAppName || 'LobeHub'}
- // Remount when the bot is saved or removed: the steps' open state is
- // mount-only and should follow whether there is anything saved.
- disabled={disabled}
- form={form}
- hasConfig={hasConfig}
- key={hasConfig ? 'saved' : 'new'}
- platformId={platformDef.id}
- platformName={platformDef.name}
- scope={quickSetupScope}
- onAuthenticated={onAuthenticated}
- />
- )}
-
- <Form.Group
- collapsible={false}
- desc={t('channel.section.connection.desc', { name: platformDef.name })}
- extra={connectionExtra}
- title={t('channel.section.connection.title')}
- variant={'filled'}
- >
+ <Form
+ form={form}
+ gap={24}
+ itemMinWidth={'max(34%, 240px)'}
+ style={{ maxWidth: 1024, padding: '8px 0 24px', width: '100%' }}
+ variant={'filled'}
+ >
+ <Panel active={activeTab === 'connect'} tab="connect">
{CustomCredentialBody ? (
- <CustomCredentialBody
- currentConfig={currentConfig}
- disabled={disabled}
- hasConfig={hasConfig}
- onAuthenticated={onAuthenticated}
- />
+ <Form.Group title={t('channel.credentials')} variant={'filled'}>
+ <CustomCredentialBody
+ currentConfig={currentConfig}
+ disabled={disabled}
+ hasConfig={hasConfig}
+ onAuthenticated={onAuthenticated}
+ />
+ </Form.Group>
) : (
<>
- {credentialRows.map(({ field, key }, index) =>
- key === 'applicationId' ? (
- <ApplicationIdField
- disabled={disabled}
- divider={index > 0}
- field={field}
- key="applicationId"
- />
- ) : (
- <SchemaField
- disabled={disabled}
- divider={index > 0}
- field={field}
- key={key}
- parentKey="credentials"
- />
- ),
- )}
- {/* Platform-specific helpers (e.g. LINE's "Fetch from LINE" button)
+ <QuickSetupSection
+ appName={quickSetupAppName || 'LobeHub'}
+ disabled={disabled}
+ form={form}
+ hasConfig={hasConfig}
+ platformId={platformDef.id}
+ renderField={inlineKeys.size > 0 ? renderStepField : undefined}
+ saving={saving}
+ scope={quickSetupScope}
+ onAuthenticated={onAuthenticated}
+ onSave={onSave}
+ />
+ {/* Credentials of a saved bot are masked and rarely edited, so they
+ fold away; a new bot has nothing else to do but fill them in. */}
+ {(groupCredentialFields.length > 0 || showApplicationId || showExtras) && (
+ <Form.Group
+ collapsible={!!hasConfig || inlineKeys.size > 0}
+ defaultActive={!hasConfig && inlineKeys.size === 0}
+ desc={t('channel.group.credentialsDesc')}
+ keyValue={`credentials-${platformDef.id}`}
+ variant={'filled'}
+ // The steps above ask for what is needed; what is left is optional.
+ title={t(
+ inlineKeys.size > 0
+ ? 'channel.group.credentialsOptional'
+ : 'channel.credentials',
+ )}
+ >
+ {/* Render top-level sections in schema order so each platform controls
+ its own field ordering. LINE places `credentials` before `applicationId`
+ because the operator must enter the channel access token before the
+ "Fetch from LINE" button (rendered after applicationId) can auto-fill
+ the destination user ID; Discord/Slack/QQ/Feishu place `applicationId`
+ first as a primary identifier. */}
+ {platformDef.schema
+ .filter(
+ (section) =>
+ (section.key === 'applicationId' && showApplicationId) ||
+ section.key === 'credentials',
+ )
+ .map((section, sectionIndex) => {
+ const needsDivider = sectionIndex > 0;
+ if (section.key === 'applicationId') {
+ return (
+ <ApplicationIdField
+ disabled={disabled}
+ divider={needsDivider}
+ field={section}
+ key="applicationId"
+ />
+ );
+ }
+ return (
+ <Fragment key="credentials">
+ {groupCredentialFields.map((field, i) => (
+ <SchemaField
+ fullWidth
+ disabled={disabled}
+ divider={needsDivider || i !== 0}
+ field={field}
+ key={field.key}
+ parentKey="credentials"
+ />
+ ))}
+ </Fragment>
+ );
+ })}
+ {/* Platform-specific helpers (e.g. LINE's "Fetch from LINE" button)
render after the credential + applicationId block so the button
sits next to the field it acts on. */}
- {CredentialExtras && <CredentialExtras disabled={disabled} />}
+ {showExtras && <CredentialExtras disabled={disabled} />}
+ </Form.Group>
+ )}
</>
)}
- {connectionSettings.map((field) => renderSettingsField(field, 1))}
- {hasConfig && <WebhookUrlField form={form} platformDef={platformDef} />}
- </Form.Group>
-
- {sections.map(({ fields, key }) => (
- <Form.Group
- collapsible={!hasConfig}
- defaultActive={!!hasConfig}
- desc={t(`channel.section.${key}.desc`, { defaultValue: '', name: platformDef.name })}
- id={SECTION_ANCHORS[key]}
- key={`${platformDef.id}:${key}:${hasConfig ? 'saved' : 'new'}`}
- keyValue={`channel-section-${key}`}
- title={t(`channel.section.${key}.title`)}
- variant={'filled'}
- >
- {fields.map(renderSettingsField)}
- </Form.Group>
- ))}
-
- {(showReset || showRemove) && (
- <Form.Group
- collapsible={false}
- title={t('channel.section.danger.title')}
- variant={'filled'}
- >
- {showReset && (
- <Form.Field
- desc={t('channel.dangerZone.resetDesc')}
- label={t('channel.settingsResetDefault')}
- >
- <Button
+ {connectGroup && (
+ <Form.Group
+ collapsible={false}
+ keyValue={`settings-connect-${platformDef.id}`}
+ title={t('channel.group.connection')}
+ variant={'filled'}
+ >
+ {connectGroup.fields.map((field, index) => (
+ <SchemaField
disabled={disabled}
- icon={<RotateCcw size={14} />}
- onClick={() =>
- confirmModal({
- content: t('channel.dangerZone.resetConfirm'),
- okText: t('channel.settingsResetDefault'),
- title: t('channel.settingsResetDefault'),
- onOk: handleResetSettings,
- })
- }
- >
- {t('channel.settingsResetDefault')}
- </Button>
- </Form.Field>
- )}
- {showRemove && (
- <Form.Field
- desc={t('channel.dangerZone.removeDesc', { name: platformDef.name })}
- divider={showReset}
- label={t('channel.removeChannel')}
+ divider={index !== 0}
+ field={field}
+ key={field.key}
+ parentKey="settings"
+ />
+ ))}
+ </Form.Group>
+ )}
+ </Panel>
+ {settingsGroups
+ .filter((group) => group.key !== 'connect')
+ .map((group) => (
+ <Panel active={activeTab === group.key} key={group.key} tab={group.key}>
+ {/* The intro explains the rules, so it shows only where they are released. */}
+ {group.key === 'wake' &&
+ group.fields.some((field) => field.key.startsWith(WAKE_KEY_PREFIX)) && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('channel.wake.intro')}
+ </Text>
+ )}
+ {group.key === 'reply' && hasConfig && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('channel.reply.instant')}
+ </Text>
+ )}
+ <Form.Group
+ collapsible={false}
+ keyValue={`settings-${group.key}-${platformDef.id}`}
+ variant={'filled'}
>
- <Button
- danger
- disabled={removeDisabled}
- icon={<Trash2 size={14} />}
- onClick={onDelete}
- >
- {t('channel.removeChannel')}
- </Button>
- </Form.Field>
- )}
- </Form.Group>
- )}
+ {group.key === 'access' &&
+ group.fields.some((f) => f.key === 'dmPolicy' || f.key === 'groupPolicy') ? (
+ <AccessSection
+ disabled={disabled}
+ fields={group.fields}
+ form={form}
+ userIdExtras={renderExtras(group.fields.find((f) => f.key === 'userId'))}
+ onValuesChange={onValuesChange}
+ />
+ ) : (
+ group.fields
+ // The master switch is always on for the people who see these options.
+ .filter((field) => field.key !== WAKE_MASTER_KEY)
+ .map((field, index) => {
+ // Feature-gated fields (e.g. watch keywords) lock when the
+ // resolved access meta reports the feature as not allowed.
+ const featureLocked =
+ !!field.paidFeature &&
+ platformDef.access?.features?.[field.paidFeature]?.allowed === false;
+ return (
+ <Fragment key={field.key}>
+ <SchemaField
+ disabled={disabled}
+ divider={index !== 0}
+ featureLocked={featureLocked}
+ field={field}
+ parentKey="settings"
+ />
+ {renderExtras(field, featureLocked)}
+ </Fragment>
+ );
+ })
+ )}
+ {group.key === 'advanced' && (
+ <Flexbox horizontal justify={'flex-end'} style={{ paddingBlock: 8 }}>
+ <Button
+ disabled={disabled}
+ icon={<RotateCcw size={14} />}
+ size="small"
+ type="text"
+ onClick={() =>
+ confirmModal({
+ content: t('channel.settingsResetConfirm'),
+ okText: t('channel.settingsResetDefault'),
+ title: t('channel.settingsResetDefault'),
+ onOk: () => handleResetGroup(group.fields),
+ })
+ }
+ >
+ {t('channel.settingsResetDefault')}
+ </Button>
+ </Flexbox>
+ )}
+ </Form.Group>
+ </Panel>
+ ))}
</Form>
);
},
diff --git a/src/features/AgentChannel/PlatformDetail/ChannelHero.tsx b/src/features/AgentChannel/PlatformDetail/ChannelHero.tsx
new file mode 100644
index 00000000000..04b4fc1f406
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ChannelHero.tsx
@@ -0,0 +1,107 @@
+'use client';
+
+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ExternalLink } from 'lucide-react';
+import { memo, type ReactNode, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+import type { BotRuntimeStatus } from '@/types/botRuntimeStatus';
+
+import { getPlatformIcon } from '../const';
+import { getSetupGuide } from '../quickSetup/guides';
+import { ChannelStatusDot } from './ChannelStatusDot';
+import { findInviteLink, maskId } from './heroModel';
+
+const styles = stylex.create({
+ logo: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderRadius: cssVar.borderRadiusLG,
+ display: 'flex',
+ flexShrink: 0,
+ height: 44,
+ justifyContent: 'center',
+ position: 'relative',
+ width: 44,
+ },
+});
+
+interface ChannelHeroProps {
+ /** The saved bot's application ID; empty before the channel is set up. */
+ applicationId?: string;
+ /** The agent the bot speaks as. */
+ botName?: string;
+ /** An extra action after the links, e.g. the button that brings the preview back. */
+ extra?: ReactNode;
+ platformDef: SerializedPlatformDefinition;
+ /** The saved bot's connection state, shown as a dot on the logo. */
+ status?: BotRuntimeStatus;
+}
+
+/**
+ * Which bot this page is about: the platform, the agent it speaks as and the
+ * app it is connected to, with the two links a person reaches for most (the
+ * platform's console and, where the platform has one, the invite link).
+ */
+export const ChannelHero = memo<ChannelHeroProps>(
+ ({ applicationId, botName, extra, platformDef, status }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string, options?: Record<string, unknown>) => string;
+
+ const PlatformIcon = getPlatformIcon(platformDef.name);
+ const ColorIcon =
+ PlatformIcon && 'Color' in PlatformIcon ? (PlatformIcon as any).Color : PlatformIcon;
+
+ const savedId = applicationId?.trim();
+ const invite = useMemo(
+ () =>
+ savedId
+ ? findInviteLink(getSetupGuide(platformDef.id, { applicationId: savedId, appName: '' }))
+ : undefined,
+ [platformDef.id, savedId],
+ );
+ const portalUrl = platformDef.documentation?.portalUrl;
+ const agent = botName?.trim() || t('channel.quickView.bot');
+
+ return (
+ <Flexbox horizontal align={'center'} data-testid={'channel-hero'} gap={12} wrap={'wrap'}>
+ <div {...stylex.props(styles.logo)}>
+ {ColorIcon && <ColorIcon size={28} />}
+ <ChannelStatusDot status={status} />
+ </div>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 200 }}>
+ <Text fontSize={18} weight={600}>
+ {t('channel.hero.title', { name: platformDef.name })}
+ </Text>
+ <Text ellipsis fontSize={13} type={'secondary'}>
+ {savedId
+ ? t('channel.hero.connected', { agent, id: maskId(savedId) })
+ : t('channel.hero.new', { agent, name: platformDef.name })}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal gap={8}>
+ {invite && (
+ <a href={invite.href} rel={'noreferrer'} target={'_blank'}>
+ <Button icon={<Icon icon={ExternalLink} />}>
+ {t('channel.quickSetup.link.inviteBot')}
+ </Button>
+ </a>
+ )}
+ {portalUrl && (
+ <a href={portalUrl} rel={'noreferrer'} target={'_blank'}>
+ <Button icon={<Icon icon={ExternalLink} />}>
+ {t('channel.quickSetup.link.openConsole')}
+ </Button>
+ </a>
+ )}
+ {extra}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+ChannelHero.displayName = 'ChannelHero';
diff --git a/src/features/AgentChannel/PlatformDetail/ChannelStatusDot.tsx b/src/features/AgentChannel/PlatformDetail/ChannelStatusDot.tsx
new file mode 100644
index 00000000000..b7b1639560a
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ChannelStatusDot.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { BOT_RUNTIME_STATUSES, type BotRuntimeStatus } from '@/types/botRuntimeStatus';
+
+const styles = stylex.create({
+ dot: {
+ blockSize: 12,
+ borderRadius: '50%',
+ // A ring in the page colour keeps the dot readable on top of the logo tile.
+ boxShadow: `0 0 0 2px ${cssVar.colorBgContainer}`,
+ display: 'block',
+ inlineSize: 12,
+ insetBlockEnd: -2,
+ insetInlineEnd: -2,
+ position: 'absolute',
+ },
+ connected: { backgroundColor: cssVar.colorSuccess },
+ disconnected: { backgroundColor: cssVar.colorTextQuaternary },
+ dormant: { backgroundColor: cssVar.colorWarning },
+ failed: { backgroundColor: cssVar.colorError },
+ pending: { backgroundColor: cssVar.colorInfo },
+});
+
+const TONES: Partial<Record<BotRuntimeStatus, keyof typeof styles>> = {
+ [BOT_RUNTIME_STATUSES.connected]: 'connected',
+ [BOT_RUNTIME_STATUSES.disconnected]: 'disconnected',
+ [BOT_RUNTIME_STATUSES.dormant]: 'dormant',
+ [BOT_RUNTIME_STATUSES.failed]: 'failed',
+ [BOT_RUNTIME_STATUSES.queued]: 'pending',
+ [BOT_RUNTIME_STATUSES.starting]: 'pending',
+};
+
+const LABELS: Partial<Record<BotRuntimeStatus, string>> = {
+ [BOT_RUNTIME_STATUSES.connected]: 'channel.statusConnected',
+ [BOT_RUNTIME_STATUSES.disconnected]: 'channel.statusDisconnected',
+ [BOT_RUNTIME_STATUSES.dormant]: 'channel.statusDormant',
+ [BOT_RUNTIME_STATUSES.failed]: 'channel.statusFailed',
+ [BOT_RUNTIME_STATUSES.queued]: 'channel.statusQueued',
+ [BOT_RUNTIME_STATUSES.starting]: 'channel.statusStarting',
+};
+
+/**
+ * The bot's connection state as a dot on the bottom-right corner of its logo, the way a chat app
+ * marks someone online. The state's name is in the tooltip and the accessible label.
+ */
+export const ChannelStatusDot = memo<{ status?: BotRuntimeStatus }>(({ status }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ const tone = status ? TONES[status] : undefined;
+ const label = status ? LABELS[status] : undefined;
+ if (!tone || !label) return null;
+
+ return (
+ <Tooltip title={t(label)}>
+ <span
+ aria-label={t(label)}
+ data-status={status}
+ role={'img'}
+ {...stylex.props(styles.dot, styles[tone])}
+ />
+ </Tooltip>
+ );
+});
+
+ChannelStatusDot.displayName = 'ChannelStatusDot';
diff --git a/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx b/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx
new file mode 100644
index 00000000000..0dc39fe74d7
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ChannelTabBar.tsx
@@ -0,0 +1,52 @@
+'use client';
+
+import { Tabs } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ChannelTab } from './channelTabs';
+
+const styles = stylex.create({
+ dot: {
+ backgroundColor: cssVar.colorWarning,
+ borderRadius: '50%',
+ display: 'inline-block',
+ height: 6,
+ marginInlineStart: 6,
+ verticalAlign: 'middle',
+ width: 6,
+ },
+});
+
+interface ChannelTabBarProps {
+ active: ChannelTab;
+ /** Tabs that still need something fixed get a small dot. */
+ issues: ChannelTab[];
+ onChange: (tab: ChannelTab) => void;
+ tabs: ChannelTab[];
+}
+
+export const ChannelTabBar = memo<ChannelTabBarProps>(({ active, issues, onChange, tabs }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string) => string;
+
+ return (
+ <Tabs
+ activeKey={active}
+ items={tabs.map((tab) => ({
+ key: tab,
+ label: (
+ <span>
+ {t(`channel.tab.${tab}`)}
+ {issues.includes(tab) && <i {...stylex.props(styles.dot)} />}
+ </span>
+ ),
+ }))}
+ onChange={(key) => onChange(key as ChannelTab)}
+ />
+ );
+});
+
+ChannelTabBar.displayName = 'ChannelTabBar';
diff --git a/src/features/AgentChannel/PlatformDetail/ChoiceList.tsx b/src/features/AgentChannel/PlatformDetail/ChoiceList.tsx
new file mode 100644
index 00000000000..7715af38e9e
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/ChoiceList.tsx
@@ -0,0 +1,141 @@
+'use client';
+
+import { Flexbox, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { type KeyboardEvent, memo } from 'react';
+
+const styles = stylex.create({
+ dot: {
+ borderColor: cssVar.colorBorder,
+ borderRadius: '50%',
+ borderStyle: 'solid',
+ borderWidth: 1.5,
+ flexShrink: 0,
+ height: 16,
+ marginBlockStart: 2,
+ width: 16,
+ },
+ dotOn: {
+ borderColor: cssVar.colorPrimary,
+ borderWidth: 5,
+ },
+ group: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 0,
+ marginInline: -12,
+ width: 'calc(100% + 24px)',
+ },
+ row: {
+ alignItems: 'flex-start',
+ backgroundColor: {
+ ':hover': cssVar.colorFillQuaternary,
+ 'default': 'transparent',
+ },
+ borderRadius: cssVar.borderRadius,
+ borderWidth: 0,
+ columnGap: 12,
+ cursor: 'pointer',
+ display: 'flex',
+ paddingBlock: 8,
+ paddingInline: 12,
+ textAlign: 'start',
+ width: '100%',
+ },
+ rowDisabled: {
+ cursor: 'not-allowed',
+ opacity: 0.5,
+ },
+ rowOn: {
+ backgroundColor: cssVar.colorFillTertiary,
+ },
+});
+
+export interface ChoiceOption<T extends string> {
+ desc?: string;
+ label: string;
+ /** Marks the option the product suggests; shown as a small tag. */
+ recommendedLabel?: string;
+ value: T;
+}
+
+interface ChoiceListProps<T extends string> {
+ 'aria-label'?: string;
+ 'disabled'?: boolean;
+ 'onChange': (value: T) => void;
+ 'options': ChoiceOption<T>[];
+ 'value': T;
+}
+
+/**
+ * A short single-choice list where every option states what it does. Used
+ * where a dropdown would hide the consequences: the options are few and each
+ * one needs a sentence. Behaves as a radio group, including arrow keys.
+ */
+const ChoiceListInner = <T extends string>({
+ 'aria-label': ariaLabel,
+ disabled,
+ onChange,
+ options,
+ value,
+}: ChoiceListProps<T>) => {
+ const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
+ const step =
+ event.key === 'ArrowDown' || event.key === 'ArrowRight'
+ ? 1
+ : event.key === 'ArrowUp' || event.key === 'ArrowLeft'
+ ? -1
+ : 0;
+ if (!step || disabled) return;
+
+ event.preventDefault();
+ const next = (index + step + options.length) % options.length;
+ onChange(options[next].value);
+ (
+ event.currentTarget.parentElement?.querySelectorAll<HTMLElement>('[role="radio"]')[next] ??
+ undefined
+ )?.focus();
+ };
+
+ return (
+ <div aria-label={ariaLabel} role="radiogroup" {...stylex.props(styles.group)}>
+ {options.map((option, index) => {
+ const on = option.value === value;
+
+ return (
+ <button
+ aria-checked={on}
+ disabled={disabled}
+ key={option.value}
+ role="radio"
+ tabIndex={on ? 0 : -1}
+ type="button"
+ {...stylex.props(styles.row, on && styles.rowOn, disabled && styles.rowDisabled)}
+ onClick={() => onChange(option.value)}
+ onKeyDown={(event) => handleKeyDown(event, index)}
+ >
+ <span {...stylex.props(styles.dot, on && styles.dotOn)} />
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text weight={500}>{option.label}</Text>
+ {option.recommendedLabel && (
+ <Tag color={'blue'} size={'small'}>
+ {option.recommendedLabel}
+ </Tag>
+ )}
+ </Flexbox>
+ {option.desc && (
+ <Text fontSize={12} type={'secondary'}>
+ {option.desc}
+ </Text>
+ )}
+ </Flexbox>
+ </button>
+ );
+ })}
+ </div>
+ );
+};
+
+export const ChoiceList = memo(ChoiceListInner) as typeof ChoiceListInner;
diff --git a/src/features/AgentChannel/PlatformDetail/Footer.tsx b/src/features/AgentChannel/PlatformDetail/Footer.tsx
new file mode 100644
index 00000000000..0fbdc4f0189
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/Footer.tsx
@@ -0,0 +1,388 @@
+'use client';
+
+import { Alert, Button, Flexbox, Tag } from '@lobehub/ui';
+import { type FormInstance, useWatch } from '@lobehub/ui/form';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { RefreshCw, Trash2 } from 'lucide-react';
+import { memo, useEffect, useMemo, useState } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { useAppOrigin } from '@/hooks/useAppOrigin';
+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+
+import type { ChannelFormValues, CurrentConfig, TestResult } from './index';
+
+/**
+ * The tint stays, the outline goes. The soft Alert draws its outline as an inset box-shadow, not a
+ * border, so that is what has to be cleared.
+ */
+const NOTICE_STYLE = { boxShadow: 'none' } as const;
+
+const styles = stylex.create({
+ actionBar: {
+ alignItems: 'center',
+ display: 'flex',
+ justifyContent: 'space-between',
+ paddingBlockStart: 16,
+ },
+ bottom: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 16,
+ maxWidth: 1024,
+ width: '100%',
+ },
+ notices: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 12,
+ marginBlockStart: { ':empty': 0, 'default': 8 },
+ maxWidth: 1024,
+ width: '100%',
+ },
+ resultDetail: {
+ color: cssVar.colorTextTertiary,
+ fontFamily: 'monospace',
+ fontSize: 12,
+ wordBreak: 'break-all',
+ },
+ webhookBox: {
+ backgroundColor: cssVar.colorFillQuaternary,
+ borderColor: cssVar.colorBorder,
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ color: cssVar.colorTextSecondary,
+ flexGrow: 1,
+ flexShrink: 1,
+ fontFamily: 'monospace',
+ fontSize: 13,
+ height: cssVar.controlHeight,
+ lineHeight: cssVar.controlHeight,
+ overflow: 'hidden',
+ paddingInline: 12,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
+
+/**
+ * Error body of a result banner: one readable sentence, with the raw platform
+ * message folded behind a "show details" toggle so it stays available for
+ * diagnosis without being dumped into the banner.
+ */
+const ResultDetail = memo<{ detail?: string; hint: string }>(({ detail, hint }) => {
+ const { t } = useTranslation('agent');
+ const [open, setOpen] = useState(false);
+ if (!detail || detail === hint) return <>{hint}</>;
+ return (
+ <Flexbox align={'flex-start'} gap={4}>
+ <span>{hint}</span>
+ <Button size={'small'} type={'text'} onClick={() => setOpen((value) => !value)}>
+ {open ? t('channel.resultDetail.hide') : t('channel.resultDetail.show')}
+ </Button>
+ {open && <span {...stylex.props(styles.resultDetail)}>{detail}</span>}
+ </Flexbox>
+ );
+});
+
+ResultDetail.displayName = 'ResultDetail';
+
+interface FooterNoticesProps {
+ connectResult?: TestResult;
+ currentConfig?: CurrentConfig;
+ form: FormInstance<ChannelFormValues>;
+ hasConfig: boolean;
+ platformDef: SerializedPlatformDefinition;
+ saveResult?: TestResult;
+ testResult?: TestResult;
+}
+
+/**
+ * What just happened to the bot (saved, connected, failed) and what it still
+ * needs. Rendered above the form: the form is long enough now that a notice
+ * under it would be scrolled past, and a failed connection is the one thing
+ * the person has to see.
+ */
+export const FooterNotices = memo<FooterNoticesProps>(
+ ({ platformDef, currentConfig, form, hasConfig, connectResult, saveResult, testResult }) => {
+ const { t } = useTranslation('agent');
+ const platformId = platformDef.id;
+ const settingsConnectionMode = useWatch(form, 'settings.connectionMode');
+
+ const showWebhookUrl = platformDef.showWebhookUrl || settingsConnectionMode === 'webhook';
+
+ // Strong reminder when an already-saved bot is missing the operator's
+ // User ID. Without it, AI tools can't push notifications back to the
+ // operator and the pairing approver identity is undefined. Skipped on
+ // first-time config and on platforms whose schema doesn't expose
+ // `userId` (e.g. WeChat, which auto-manages identity via QR).
+ const hasUserIdField = useMemo(() => {
+ const settings = platformDef.schema.find((f) => f.key === 'settings');
+ return settings?.properties?.some((f) => f.key === 'userId') ?? false;
+ }, [platformDef.schema]);
+ const watchedUserId = useWatch(form, 'settings.userId');
+ // `useWatch` returns `undefined` until the form hydrates from the
+ // parent's `initialValues`. Fall back to the saved value only during
+ // that pre-hydration window so we don't flash the alert for every
+ // saved bot. Once the form has reported a value, trust the watched
+ // value — including `undefined`, so "Reset to Default" (which clears
+ // settings.userId) correctly re-surfaces the alert.
+ const savedUserId = currentConfig?.settings?.userId;
+ const [formHydrated, setFormHydrated] = useState(false);
+ useEffect(() => {
+ if (watchedUserId !== undefined) setFormHydrated(true);
+ }, [watchedUserId]);
+ const effectiveUserId = formHydrated ? watchedUserId : savedUserId;
+ const userIdMissing =
+ hasConfig &&
+ hasUserIdField &&
+ !(typeof effectiveUserId === 'string' && effectiveUserId.trim());
+
+ return (
+ <div {...stylex.props(styles.notices)}>
+ {saveResult && (
+ <Alert
+ closable
+ showIcon
+ style={NOTICE_STYLE}
+ title={saveResult.type === 'success' ? t('channel.saved') : t('channel.saveFailed')}
+ type={saveResult.type}
+ description={
+ saveResult.type === 'error' ? (
+ <ResultDetail
+ detail={saveResult.errorDetail}
+ hint={saveResult.hint || t('channel.saveFailedHint')}
+ />
+ ) : undefined
+ }
+ />
+ )}
+
+ {connectResult && (
+ <Alert
+ closable
+ showIcon
+ style={NOTICE_STYLE}
+ type={connectResult.type}
+ description={
+ connectResult.type === 'error' ? (
+ <ResultDetail
+ detail={connectResult.errorDetail}
+ hint={connectResult.hint || t('channel.connectFailedHint')}
+ />
+ ) : undefined
+ }
+ title={
+ connectResult.title ||
+ (connectResult.type === 'success'
+ ? t('channel.connectSuccess')
+ : t('channel.connectFailed'))
+ }
+ />
+ )}
+
+ {testResult && (
+ <Alert
+ closable
+ showIcon
+ style={NOTICE_STYLE}
+ type={testResult.type}
+ description={
+ testResult.type === 'error' ? (
+ <ResultDetail
+ detail={testResult.errorDetail}
+ hint={testResult.hint || t('channel.testFailedHint')}
+ />
+ ) : undefined
+ }
+ title={
+ testResult.type === 'success' ? t('channel.testSuccess') : t('channel.testFailed')
+ }
+ />
+ )}
+
+ {userIdMissing && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.userIdMissingDesc')}
+ message={t('channel.userIdMissingTitle')}
+ style={NOTICE_STYLE}
+ type="info"
+ />
+ )}
+
+ {hasConfig && showWebhookUrl && platformId === 'qq' && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.qq.webhookMigrationDesc')}
+ message={t('channel.qq.webhookMigrationTitle')}
+ style={NOTICE_STYLE}
+ type="info"
+ />
+ )}
+
+ {hasConfig && showWebhookUrl && platformId === 'slack' && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.slack.webhookMigrationDesc')}
+ message={t('channel.slack.webhookMigrationTitle')}
+ style={NOTICE_STYLE}
+ type="info"
+ />
+ )}
+
+ {hasConfig && showWebhookUrl && (platformId === 'feishu' || platformId === 'lark') && (
+ <Alert
+ closable
+ showIcon
+ description={t('channel.feishu.webhookMigrationDesc')}
+ message={t('channel.feishu.webhookMigrationTitle')}
+ style={NOTICE_STYLE}
+ type="info"
+ />
+ )}
+ </div>
+ );
+ },
+);
+
+FooterNotices.displayName = 'ChannelFooterNotices';
+
+interface FooterActionsProps {
+ connecting: boolean;
+ disabled?: boolean;
+ form: FormInstance<ChannelFormValues>;
+ hasConfig: boolean;
+ /** The setup steps already offer the save, so the bar does not repeat it. */
+ hideSave?: boolean;
+ isDirty: boolean;
+ onCopied: () => void;
+ onDelete: () => void;
+ onDiscard: () => void;
+ onSave: () => void;
+ onTestConnection: () => void;
+ platformDef: SerializedPlatformDefinition;
+ saving: boolean;
+ testing: boolean;
+ writeDisabled?: boolean;
+}
+
+/** The buttons that act on the form, and the endpoint URL a webhook bot hands to the platform. */
+export const FooterActions = memo<FooterActionsProps>(
+ ({
+ platformDef,
+ form,
+ hasConfig,
+ hideSave,
+ isDirty,
+ connecting,
+ disabled,
+ saving,
+ testing,
+ writeDisabled,
+ onSave,
+ onDelete,
+ onDiscard,
+ onTestConnection,
+ onCopied,
+ }) => {
+ const { t } = useTranslation('agent');
+ const origin = useAppOrigin();
+ const platformId = platformDef.id;
+ const applicationId = useWatch(form, 'applicationId');
+ const settingsConnectionMode = useWatch(form, 'settings.connectionMode');
+ const showWebhookUrl = platformDef.showWebhookUrl || settingsConnectionMode === 'webhook';
+
+ const webhookUrl = applicationId
+ ? `${origin}/api/agent/webhooks/${platformId}/${applicationId}`
+ : `${origin}/api/agent/webhooks/${platformId}`;
+
+ return (
+ <div {...stylex.props(styles.bottom)}>
+ <div {...stylex.props(styles.actionBar)}>
+ {hasConfig ? (
+ <Button
+ danger
+ disabled={disabled || saving || connecting}
+ icon={<Trash2 size={16} />}
+ onClick={onDelete}
+ >
+ {t('channel.removeChannel')}
+ </Button>
+ ) : (
+ <div />
+ )}
+ <Flexbox horizontal gap={12}>
+ {hasConfig && (
+ <Button
+ disabled={writeDisabled || saving || connecting}
+ icon={<RefreshCw size={16} />}
+ loading={testing}
+ onClick={onTestConnection}
+ >
+ {t('channel.testConnection')}
+ </Button>
+ )}
+ {isDirty && (
+ <Button disabled={writeDisabled || saving || connecting} onClick={onDiscard}>
+ {t('channel.discard')}
+ </Button>
+ )}
+ {!hideSave && (
+ <Button
+ disabled={writeDisabled}
+ loading={saving || connecting}
+ type="primary"
+ onClick={onSave}
+ >
+ {connecting
+ ? t('channel.connecting')
+ : t(hasConfig ? 'channel.save' : 'channel.saveAndConnect')}
+ </Button>
+ )}
+ </Flexbox>
+ </div>
+
+ {hasConfig && showWebhookUrl && (
+ <Flexbox gap={8}>
+ <Flexbox horizontal align="center" gap={8}>
+ <span style={{ fontWeight: 600 }}>{t('channel.endpointUrl')}</span>
+ <Tag>{'Event Subscription URL'}</Tag>
+ </Flexbox>
+ <Flexbox horizontal gap={8}>
+ <div {...stylex.props(styles.webhookBox)}>{webhookUrl}</div>
+ <Button
+ onClick={() => {
+ navigator.clipboard.writeText(webhookUrl);
+ onCopied();
+ }}
+ >
+ {t('channel.copy')}
+ </Button>
+ </Flexbox>
+ <Alert
+ showIcon
+ style={NOTICE_STYLE}
+ type="info"
+ message={
+ <Trans<'channel.endpointUrlHint', 'agent'>
+ components={{ bold: <strong /> }}
+ i18nKey="channel.endpointUrlHint"
+ ns="agent"
+ values={{ fieldName: 'Event Subscription URL', name: platformDef.name }}
+ />
+ }
+ />
+ </Flexbox>
+ )}
+ </div>
+ );
+ },
+);
+
+FooterActions.displayName = 'ChannelFooterActions';
diff --git a/src/features/AgentChannel/PlatformDetail/QuickView.tsx b/src/features/AgentChannel/PlatformDetail/QuickView.tsx
new file mode 100644
index 00000000000..fcbaee1c9ea
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/QuickView.tsx
@@ -0,0 +1,287 @@
+'use client';
+
+import { Flexbox, Segmented, Text } from '@lobehub/ui';
+import { type FormInstance, useWatch } from '@lobehub/ui/form';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, type ReactNode, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Avatar from '@/components/Avatar';
+import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
+
+import type { ChannelFormValues } from './index';
+import {
+ pickKeywords,
+ type PreviewScene,
+ type PreviewSettings,
+ resolveDmOutcome,
+ resolveGroupOutcome,
+ resolveScenes,
+} from './previewModel';
+
+// Discord's own brand colour, used only on the marks that identify its messages.
+// lobe-design-ignore LOBE-RAW-COLOR: platform brand colour
+const DISCORD_BLURPLE = '#5865F2';
+
+const styles = stylex.create({
+ bubble: {
+ backgroundColor: cssVar.colorFillTertiary,
+ borderRadius: cssVar.borderRadius,
+ color: cssVar.colorText,
+ fontSize: 13,
+ lineHeight: 1.6,
+ paddingBlock: 8,
+ paddingInline: 12,
+ wordBreak: 'break-word',
+ },
+ mention: {
+ color: cssVar.colorPrimary,
+ },
+ appTag: {
+ backgroundColor: DISCORD_BLURPLE,
+ borderRadius: 3,
+ color: '#fff', // lobe-design-ignore LOBE-RAW-COLOR: text on the platform's brand tag
+ fontSize: 10,
+ fontWeight: 600,
+ lineHeight: '14px',
+ paddingBlock: 1,
+ paddingInline: 4,
+ },
+ senderAvatar: {
+ alignItems: 'center',
+ backgroundColor: cssVar.colorFillSecondary,
+ borderRadius: '50%',
+ color: cssVar.colorTextSecondary,
+ display: 'flex',
+ flexShrink: 0,
+ fontSize: 14,
+ fontWeight: 600,
+ height: 36,
+ justifyContent: 'center',
+ width: 36,
+ },
+ discordBody: {
+ color: cssVar.colorText,
+ fontSize: 14,
+ lineHeight: 1.5,
+ wordBreak: 'break-word',
+ },
+ discordMention: {
+ backgroundColor: `color-mix(in srgb, ${DISCORD_BLURPLE} 16%, transparent)`,
+ borderRadius: 3,
+ color: DISCORD_BLURPLE,
+ paddingInline: 2,
+ },
+ discordName: {
+ color: cssVar.colorText,
+ fontSize: 14,
+ fontWeight: 600,
+ },
+ mono: {
+ color: cssVar.colorTextTertiary,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ },
+ // No panel fill and no card: the chat sits straight on the page beside the form.
+ panel: {
+ paddingBlock: 0,
+ },
+ stage: {
+ minHeight: 240,
+ paddingBlockStart: 8,
+ },
+ toolCall: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ color: cssVar.colorTextSecondary,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ paddingBlock: 6,
+ paddingInline: 12,
+ },
+});
+
+type Skin = 'bubble' | 'discord';
+
+/** Platforms that have their own message look in the preview; the rest share bubbles. */
+const skinFor = (platformId: string): Skin => (platformId === 'discord' ? 'discord' : 'bubble');
+
+interface RowProps {
+ avatar: ReactNode;
+ children: ReactNode;
+ name: string;
+ skin: Skin;
+ tag?: ReactNode;
+}
+
+/** One message: a name over a bubble, or Discord's avatar-beside-text layout. */
+const Row = ({ avatar, children, name, skin, tag }: RowProps) =>
+ skin === 'discord' ? (
+ <Flexbox horizontal align={'flex-start'} gap={12}>
+ {avatar}
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={6}>
+ <span {...stylex.props(styles.discordName)}>{name}</span>
+ {tag}
+ </Flexbox>
+ {children}
+ </Flexbox>
+ </Flexbox>
+ ) : (
+ <Flexbox gap={4}>
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {name}
+ </Text>
+ {children}
+ </Flexbox>
+ );
+
+/** The words of a message, in a bubble or as plain Discord text. */
+const Words = ({ children, skin }: { children: ReactNode; skin: Skin }) => (
+ <div {...stylex.props(skin === 'discord' ? styles.discordBody : styles.bubble)}>{children}</div>
+);
+
+interface QuickViewProps {
+ /** The agent's avatar and its background, shown on the bot's messages. */
+ botAvatar?: { avatar?: string; background?: string };
+ /** The agent's name, shown as the bot's name in the preview. */
+ botName?: string;
+ /** Something at the right of the title, e.g. the button that folds the preview away. */
+ extra?: ReactNode;
+ form: FormInstance<ChannelFormValues>;
+ /** The title is shown by whatever holds the preview (the drawer). */
+ hideTitle?: boolean;
+ platformDef: SerializedPlatformDefinition;
+}
+
+/**
+ * A glance at what the bot does with the settings as they stand right now: one
+ * message in a group, one in a DM, answered the way the access rules decide.
+ * It reads the live form, so every change shows up before it is saved. The
+ * wording of the bot's own system replies is illustrative.
+ */
+export const QuickView = memo<QuickViewProps>(
+ ({ botAvatar, botName, extra, form, hideTitle, platformDef }) => {
+ const { t: _t } = useTranslation('agent');
+ const t = _t as (key: string, options?: Record<string, unknown>) => string;
+
+ const settings = (useWatch(form, (values) => values.settings) ?? {}) as PreviewSettings & {
+ displayToolCalls?: boolean;
+ showUsageStats?: boolean;
+ };
+
+ const scenes = useMemo(() => {
+ const section = platformDef.schema.find((field) => field.key === 'settings');
+ return resolveScenes(section?.properties?.map((field) => field.key) ?? []);
+ }, [platformDef.schema]);
+
+ const [chosen, setChosen] = useState<PreviewScene>('group');
+ const scene = scenes.includes(chosen) ? chosen : 'group';
+
+ const name = botName?.trim() || t('channel.quickView.bot');
+ const stranger = t('channel.quickView.stranger');
+ const skin = skinFor(platformDef.id);
+ const outcome = scene === 'dm' ? resolveDmOutcome(settings) : resolveGroupOutcome(settings);
+ const keywords = pickKeywords(settings.watchKeywords);
+
+ return (
+ <Flexbox {...stylex.props(styles.panel)} data-testid={'channel-quick-view'} gap={12}>
+ <Flexbox horizontal align={'flex-start'} gap={8} justify={'space-between'}>
+ <Flexbox gap={2}>
+ {!hideTitle && (
+ <Text fontSize={16} weight={600}>
+ {t('channel.quickView.title')}
+ </Text>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {t('channel.quickView.desc')}
+ </Text>
+ </Flexbox>
+ {extra}
+ </Flexbox>
+
+ {scenes.length > 1 && (
+ <Segmented
+ block
+ size={'small'}
+ value={scene}
+ options={[
+ { label: t('channel.quickView.sceneGroup'), value: 'group' },
+ { label: t('channel.quickView.sceneDm'), value: 'dm' },
+ ]}
+ onChange={(value) => setChosen(value as PreviewScene)}
+ />
+ )}
+
+ <Flexbox {...stylex.props(styles.stage)} gap={16}>
+ <Row
+ avatar={<span {...stylex.props(styles.senderAvatar)}>{stranger.slice(0, 1)}</span>}
+ name={stranger}
+ skin={skin}
+ >
+ <Words skin={skin}>
+ {scene === 'dm' ? (
+ t('channel.quickView.askDm')
+ ) : (
+ <>
+ <span
+ {...stylex.props(skin === 'discord' ? styles.discordMention : styles.mention)}
+ >
+ @{name}
+ </span>{' '}
+ {t('channel.quickView.ask')}
+ </>
+ )}
+ </Words>
+ </Row>
+
+ <Row
+ name={name}
+ skin={skin}
+ tag={skin === 'discord' ? <span {...stylex.props(styles.appTag)}>APP</span> : undefined}
+ avatar={
+ <Avatar
+ avatar={botAvatar?.avatar}
+ background={botAvatar?.background}
+ name={name}
+ shape={'circle'}
+ size={36}
+ />
+ }
+ >
+ {outcome.kind === 'notice' && (
+ <Words skin={skin}>{t(`channel.quickView.${outcome.noticeKey}`)}</Words>
+ )}
+ {outcome.kind === 'answer' && (
+ <>
+ {settings.displayToolCalls && (
+ <div {...stylex.props(styles.toolCall)}>{t('channel.quickView.toolCall')}</div>
+ )}
+ <Words skin={skin}>{t('channel.quickView.answer')}</Words>
+ {settings.showUsageStats && (
+ <span {...stylex.props(styles.mono)}>1.2k tokens · $0.004 · 3.2s</span>
+ )}
+ {outcome.scopeNote && (
+ <Text fontSize={12} type={'secondary'}>
+ {t(`channel.quickView.${outcome.scopeNote}`)}
+ </Text>
+ )}
+ </>
+ )}
+ </Row>
+
+ {scene === 'group' && keywords.length > 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('channel.quickView.keywords', { keywords: keywords.join(' / ') })}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+QuickView.displayName = 'ChannelQuickView';
diff --git a/src/features/AgentChannel/PlatformDetail/SaveBar.tsx b/src/features/AgentChannel/PlatformDetail/SaveBar.tsx
deleted file mode 100644
index 00995c8bc32..00000000000
--- a/src/features/AgentChannel/PlatformDetail/SaveBar.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-'use client';
-
-import { Button, Flexbox, Text } from '@lobehub/ui';
-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
-import * as stylex from '@stylexjs/stylex';
-import { memo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-const styles = stylex.create({
- bar: {
- backgroundColor: cssVar.colorBgContainer,
- borderBlockStartColor: cssVar.colorBorderSecondary,
- borderBlockStartStyle: 'solid',
- borderBlockStartWidth: 1,
- display: 'flex',
- insetBlockEnd: 0,
- justifyContent: 'center',
- paddingBlock: 12,
- paddingInline: 24,
- position: 'sticky',
- width: '100%',
- zIndex: 10,
- },
- inner: {
- maxWidth: 1024,
- width: '100%',
- },
-});
-
-interface SaveBarProps {
- connecting: boolean;
- hasConfig: boolean;
- isDirty: boolean;
- onDiscard: () => void;
- onSave: () => void;
- saving: boolean;
- writeDisabled?: boolean;
-}
-
-/**
- * Pinned to the bottom of the page so saving stays in reach wherever the
- * operator is editing. Saving also (re)connects the bot, so the first save says
- * so and the button reports the connect step.
- */
-const SaveBar = memo<SaveBarProps>(
- ({ connecting, hasConfig, isDirty, onDiscard, onSave, saving, writeDisabled }) => {
- const { t } = useTranslation('agent');
- const busy = saving || connecting;
-
- const status = isDirty
- ? t('channel.saveBar.unsaved')
- : hasConfig
- ? undefined
- : t('channel.saveBar.firstSave');
-
- return (
- <div {...stylex.props(styles.bar)} data-testid={'channel-save-bar'}>
- <Flexbox horizontal align={'center'} gap={12} {...stylex.props(styles.inner)}>
- <Text style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
- {status}
- </Text>
- {isDirty && (
- <Button disabled={writeDisabled || busy} onClick={onDiscard}>
- {t('channel.discard')}
- </Button>
- )}
- <Button
- disabled={writeDisabled}
- loading={busy}
- type={isDirty || !hasConfig ? 'primary' : 'default'}
- onClick={onSave}
- >
- {connecting
- ? t('channel.connecting')
- : hasConfig
- ? t('channel.save')
- : t('channel.saveAndConnect')}
- </Button>
- </Flexbox>
- </div>
- );
- },
-);
-
-SaveBar.displayName = 'ChannelSaveBar';
-
-export default SaveBar;
diff --git a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
index 3302de8d877..78d91ee5a8c 100644
--- a/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
+++ b/src/features/AgentChannel/PlatformDetail/SchemaField.tsx
@@ -2,10 +2,8 @@
import { isMaskedBotCredential } from '@lobechat/const';
import type { SelectOption } from '@lobehub/ui';
-import { Button, Flexbox, InputNumber, Select, Switch, Tag, Text } from '@lobehub/ui';
+import { ActionIcon, Button, Flexbox, InputNumber, Select, Switch, Tag, Text } from '@lobehub/ui';
import { Form, useFormInstance, useWatch } from '@lobehub/ui/form';
-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
-import * as stylex from '@stylexjs/stylex';
import { Plus, Trash2 } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,35 +12,12 @@ import { FormInput, FormPassword } from '@/components/FormInput';
import InfoTooltip from '@/components/InfoTooltip';
import type { FieldSchema } from '@/server/services/bot/platforms/types';
-import { isFieldReleased } from './formState';
-
-/**
- * Text inputs take the Settings pages' width (`FORM_STYLE.itemMinWidth`); selects, numbers and
- * switches size to their content.
- */
-export const CHANNEL_INPUT_MIN_WIDTH = 'max(34%, 240px)';
-
-const styles = stylex.create({
- hint: {
- color: cssVar.colorTextTertiary,
- fontSize: 12,
- paddingBlock: 4,
- },
- limitHint: {
- color: cssVar.colorError,
- fontSize: 12,
- paddingBlock: 4,
- },
-});
-
-type Translate = (key: string) => string;
-
// --------------- Validation rules builder ---------------
const isEmptyValue = (value: unknown) =>
value === undefined || value === null || value === '' || (Array.isArray(value) && !value.length);
-export function buildValidate(field: FieldSchema, t: Translate) {
+export function buildValidate(field: FieldSchema, t: (key: string) => string) {
const pattern = field.pattern ? new RegExp(field.pattern) : undefined;
const isNumber = field.type === 'number' || field.type === 'integer';
const { maximum, minimum } = field;
@@ -79,9 +54,9 @@ export function buildValidate(field: FieldSchema, t: Translate) {
};
}
-// --------------- Label and description ---------------
+// --------------- Shared pieces ---------------
-const renderFieldLabel = (field: FieldSchema, t: Translate) => {
+export const renderFieldLabel = (field: FieldSchema, t: (key: string) => string) => {
const hint = field.tooltip;
if (!hint && !field.devOnly && !field.paidFeature) return t(field.label);
@@ -100,25 +75,48 @@ const renderFieldLabel = (field: FieldSchema, t: Translate) => {
);
};
-/** What the value does, in one line under the label — the schema's own description. */
-const renderFieldDesc = (field: FieldSchema, t: Translate) =>
- field.description ? t(field.description) : undefined;
+// A row is a label + one line of help on the left and a short control on the
+// right. Long free-text values (credentials, IDs lists) take the whole row.
+const CONTROL_WIDTH = 'min(240px, 100%)';
// --------------- Single field component (memo'd) ---------------
interface SchemaFieldProps {
+ /** Replaces the schema's description line, e.g. with a warning that depends on other values. */
+ descOverride?: React.ReactNode;
disabled?: boolean;
divider?: boolean;
+ /** Replaces the "nothing added yet" line of a list field. */
+ emptyOverride?: string;
/** The field belongs to a gated feature the current plan doesn't include. */
featureLocked?: boolean;
field: FieldSchema;
+ /** Stack the label over a full-width control, for long values like secrets. */
+ fullWidth?: boolean;
+ /** Keep the field mounted (so its value is kept and saved) but not shown. */
+ hidden?: boolean;
+ labelOverride?: React.ReactNode;
parentKey: string;
+ /** Replaces the schema-derived validation rule. */
+ validateOverride?: (value: unknown) => string | undefined;
}
export const SchemaField = memo<SchemaFieldProps>(
- ({ field, parentKey, divider, disabled: formDisabled, featureLocked }) => {
+ ({
+ field,
+ parentKey,
+ divider,
+ disabled: formDisabled,
+ featureLocked,
+ fullWidth,
+ hidden,
+ descOverride,
+ emptyOverride,
+ labelOverride,
+ validateOverride,
+ }) => {
const { t: _t } = useTranslation('agent');
- const t = _t as Translate;
+ const t = _t as (key: string) => string;
// Scalar controls fully lock with the feature; list fields handle the
// locked state themselves so operators can still remove stale rows.
@@ -129,6 +127,9 @@ export const SchemaField = memo<SchemaFieldProps>(
const watchedValue = useWatch(form, (values) =>
field.visibleWhen ? values[parentKey]?.[field.visibleWhen.field] : undefined,
);
+ const selectedValue = useWatch(form, (values) =>
+ field.enum ? values[parentKey]?.[field.key] : undefined,
+ );
if (field.visibleWhen) {
// An array matches any of its entries, so one field can be shared by
// several sibling values (e.g. the window size for `burst` + `debounce`).
@@ -139,39 +140,49 @@ export const SchemaField = memo<SchemaFieldProps>(
if (!matches) return null;
}
- const label = renderFieldLabel(field, t);
- const desc = renderFieldDesc(field, t);
+ const label = labelOverride ?? renderFieldLabel(field, t);
+
+ // The help line follows the choice: once someone picks a policy, what that
+ // policy does is worth more than the generic description of the field.
+ const selectedIndex = field.enum ? field.enum.indexOf(selectedValue as string) : -1;
+ const selectedHint = field.enumDescriptions?.[selectedIndex];
+ const descKey = selectedHint || field.description;
+ const desc = descOverride ?? (descKey ? t(descKey) : undefined);
// Array of objects (e.g. user / channel allowlist) — needs Form.List, can't
// be expressed as a single control inside a name-bound Form.Field.
if (field.type === 'array' && field.items?.type === 'object') {
return (
- <ObjectListField
- desc={desc}
- disabled={formDisabled}
- divider={divider}
- featureLocked={featureLocked}
- field={field}
- label={label}
- parentKey={parentKey}
- />
+ <div hidden={hidden}>
+ <ObjectListField
+ desc={desc}
+ disabled={formDisabled}
+ divider={divider}
+ emptyOverride={emptyOverride}
+ featureLocked={featureLocked}
+ field={field}
+ label={label}
+ parentKey={parentKey}
+ />
+ </div>
);
}
- const placeholder = field.placeholder ? t(field.placeholder) : undefined;
+ const placeholder = field.placeholder ? t(field.placeholder) : t(field.label);
let children: React.ReactNode;
- let minWidth: string | undefined = CHANNEL_INPUT_MIN_WIDTH;
-
switch (field.type) {
case 'password': {
children = (
- <FormPassword autoComplete="new-password" disabled={disabled} placeholder={placeholder} />
+ <FormPassword
+ autoComplete="new-password"
+ disabled={disabled}
+ placeholder={field.placeholder ? t(field.placeholder) : undefined}
+ />
);
break;
}
case 'boolean': {
children = <Switch disabled={disabled} />;
- minWidth = undefined;
break;
}
case 'number':
@@ -181,39 +192,37 @@ export const SchemaField = memo<SchemaFieldProps>(
disabled={disabled}
max={field.maximum}
min={field.minimum}
- placeholder={placeholder}
+ placeholder={field.placeholder ? t(field.placeholder) : undefined}
style={{ width: 160 }}
/>
);
- minWidth = undefined;
break;
}
- default: {
- if (field.type === 'string' && field.enum) {
- const hasDescriptions = field.enumDescriptions?.some(Boolean);
+ case 'string': {
+ if (field.enum) {
const options = field.enum.map((value, i) => ({
description: field.enumDescriptions?.[i] ? t(field.enumDescriptions[i]) : undefined,
label: field.enumLabels?.[i] ? t(field.enumLabels[i]) : value,
value,
})) satisfies Array<SelectOption<string> & { description?: string }>;
+ const hasDescriptions = options.some((option) => option.description);
children = (
<Select
disabled={disabled}
options={options}
- placeholder={placeholder}
- popupMatchSelectWidth={false}
- style={{ minWidth: 200 }}
+ placeholder={field.placeholder ? t(field.placeholder) : undefined}
+ style={{ width: CONTROL_WIDTH }}
optionRender={
hasDescriptions
? (item) => {
const option = item as SelectOption<string> & { description?: string };
return (
- <Flexbox gap={2} style={{ maxWidth: 360, paddingBlock: 2 }}>
+ <Flexbox gap={2}>
<span>{option.label}</span>
{option.description && (
- <Text fontSize={12} style={{ whiteSpace: 'normal' }} type="secondary">
+ <Text fontSize={12} type="secondary">
{option.description}
</Text>
)}
@@ -224,25 +233,41 @@ export const SchemaField = memo<SchemaFieldProps>(
}
/>
);
- minWidth = undefined;
} else {
- children = <FormInput disabled={disabled} placeholder={placeholder ?? t(field.label)} />;
+ children = (
+ <FormInput
+ disabled={disabled}
+ placeholder={placeholder}
+ style={fullWidth ? undefined : { width: CONTROL_WIDTH }}
+ />
+ );
}
+ break;
+ }
+ default: {
+ children = (
+ <FormInput
+ disabled={disabled}
+ placeholder={placeholder}
+ style={fullWidth ? undefined : { width: CONTROL_WIDTH }}
+ />
+ );
}
}
return (
- <Form.Field
- desc={desc}
- divider={divider}
- label={label}
- minWidth={minWidth}
- name={`${parentKey}.${field.key}`}
- validate={buildValidate(field, t)}
- variant="outlined"
- >
- {children}
- </Form.Field>
+ <div hidden={hidden}>
+ <Form.Field
+ desc={desc}
+ divider={divider}
+ label={label}
+ layout={fullWidth || field.type === 'password' ? 'vertical' : 'horizontal'}
+ name={`${parentKey}.${field.key}`}
+ validate={validateOverride ?? buildValidate(field, t)}
+ >
+ {children}
+ </Form.Field>
+ </div>
);
},
);
@@ -255,6 +280,7 @@ interface ObjectListFieldProps {
desc?: React.ReactNode;
disabled?: boolean;
divider?: boolean;
+ emptyOverride?: string;
/** The field belongs to a gated feature the current plan doesn't include. */
featureLocked?: boolean;
field: FieldSchema;
@@ -263,14 +289,14 @@ interface ObjectListFieldProps {
}
const ObjectListField = memo<ObjectListFieldProps>(
- ({ field, parentKey, divider, desc, label, disabled, featureLocked }) => {
+ ({ desc, emptyOverride, field, parentKey, divider, label, disabled, featureLocked }) => {
const { t: _t } = useTranslation('agent');
- const t = _t as Translate;
+ const t = _t as (key: string) => string;
// A locked feature blocks new rows and edits, but existing rows must stay
// removable — the server-side write gate always allows clearing keywords,
// and stale rows would otherwise keep the feature semi-active with no way
- // out short of resetting all settings.
+ // out short of resetting all advanced settings.
const editDisabled = disabled || featureLocked;
// The runtime ignores anything beyond `id`, but the editor renders every
@@ -283,37 +309,37 @@ const ObjectListField = memo<ObjectListFieldProps>(
// Avoids overloading FieldSchema with cosmetic strings while keeping each
// list's "Add user" / "Add channel" wording distinct.
const addLabel = t(`${field.label}Add` as 'channel.allowFromAdd');
- const emptyLabel = t(`${field.label}Empty` as 'channel.allowFromEmpty');
+ const emptyLabel = emptyOverride ?? t(`${field.label}Empty` as 'channel.allowFromEmpty');
const removeLabel = t('channel.allowListRemove');
// `maximum` mirrors the runtime parser's own cap. An over-cap list is dropped wholesale there
- // — for an allowlist that means "restrict nothing" — so the editor stops growing at the cap
- // and flags a list that already arrived over it (hand-written config, or a save from before
- // the cap existed). The save path refuses such a value; see `findOverLimitSettings`.
+ // (for an allowlist that means "restrict nothing"), so the editor stops growing at the cap and
+ // flags a list that already arrived over it. The save path refuses such a value; see
+ // `findOverLimitSettings`.
const limit = typeof field.maximum === 'number' ? field.maximum : undefined;
const limitMessage = limit
- ? t('channel.channelListLimit').replace('{{max}}', String(limit))
+ ? (t('channel.channelListLimit') as string).replace('{{max}}', String(limit))
: undefined;
return (
- <Form.Field
- desc={desc}
- divider={divider}
- label={label}
- layout={'vertical'}
- variant="outlined"
- >
+ <Form.Field desc={desc} divider={divider} label={label} layout="vertical">
<Form.List name={`${parentKey}.${field.key}`}>
{({ fields: rows, add, remove }) => (
<Flexbox gap={8} style={{ width: '100%' }}>
{limit !== undefined && rows.length > limit && (
- <div {...stylex.props(styles.limitHint)}>{limitMessage}</div>
+ <Text fontSize={12} type="danger">
+ {limitMessage}
+ </Text>
+ )}
+ {rows.length === 0 && (
+ <Text fontSize={12} type="secondary">
+ {emptyLabel}
+ </Text>
)}
- {rows.length === 0 && <div {...stylex.props(styles.hint)}>{emptyLabel}</div>}
{rows.map(({ index, key, name }) => (
<Flexbox horizontal align="center" gap={8} key={key}>
- {itemProps.map((sub) => (
- <div key={sub.key} style={{ flex: 1, minWidth: 0 }}>
+ {itemProps.map((sub, subIndex) => (
+ <div key={sub.key} style={{ flex: subIndex === 0 ? 1 : 2, minWidth: 0 }}>
<Form.Field
bare
name={`${name}.${sub.key}`}
@@ -334,22 +360,26 @@ const ObjectListField = memo<ObjectListFieldProps>(
</Form.Field>
</div>
))}
- <Button
+ <ActionIcon
aria-label={removeLabel}
disabled={disabled}
- icon={<Trash2 size={14} />}
- type="text"
+ icon={Trash2}
+ title={removeLabel}
onClick={() => remove(index)}
/>
</Flexbox>
))}
{featureLocked && (
- <div {...stylex.props(styles.hint)}>{t('channel.paidFeature.fieldLocked')}</div>
+ <Text fontSize={12} type="secondary">
+ {t('channel.paidFeature.fieldLocked')}
+ </Text>
)}
<Button
disabled={editDisabled || (limit !== undefined && rows.length >= limit)}
icon={<Plus size={14} />}
+ size="small"
style={{ alignSelf: 'flex-start' }}
+ type="text"
onClick={() => add({ id: '', name: '' })}
>
{addLabel}
@@ -372,17 +402,16 @@ export const ApplicationIdField = memo<{
field: FieldSchema;
}>(({ field, divider, disabled }) => {
const { t: _t } = useTranslation('agent');
- const t = _t as Translate;
+ const t = _t as (key: string) => string;
return (
<Form.Field
- desc={renderFieldDesc(field, t)}
+ desc={field.description ? t(field.description) : undefined}
divider={divider}
label={renderFieldLabel(field, t)}
- minWidth={CHANNEL_INPUT_MIN_WIDTH}
+ layout="vertical"
name="applicationId"
validate={buildValidate(field, t)}
- variant="outlined"
>
<FormInput
disabled={disabled}
@@ -393,23 +422,3 @@ export const ApplicationIdField = memo<{
});
ApplicationIdField.displayName = 'ChannelApplicationIdField';
-
-// --------------- Helper: flatten fields from schema ---------------
-
-export function getFields(
- schema: FieldSchema[],
- sectionKey: string,
- featureFlags?: Record<string, unknown>,
-): FieldSchema[] {
- const section = schema.find((f) => f.key === sectionKey);
- if (!section?.properties) return [];
-
- const shown = (f: FieldSchema) => (!f.devOnly || __DEV__) && isFieldReleased(f, featureFlags);
-
- return section.properties.filter(shown).flatMap((f) => {
- if (f.type === 'object' && f.properties) {
- return f.properties.filter(shown);
- }
- return f;
- });
-}
diff --git a/src/features/AgentChannel/PlatformDetail/StatusAlerts.tsx b/src/features/AgentChannel/PlatformDetail/StatusAlerts.tsx
deleted file mode 100644
index ed28a2b9e46..00000000000
--- a/src/features/AgentChannel/PlatformDetail/StatusAlerts.tsx
+++ /dev/null
@@ -1,209 +0,0 @@
-'use client';
-
-import { Alert, Button, Flexbox } from '@lobehub/ui';
-import { type FormInstance, useWatch } from '@lobehub/ui/form';
-import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
-import * as stylex from '@stylexjs/stylex';
-import { memo, type Ref, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
-
-import type { ChannelFormValues, CurrentConfig, TestResult } from './index';
-
-/** Anchor on the "Your account" section, so the missing-User-ID alert can jump to it. */
-export const ACCOUNT_SECTION_ID = 'channel-section-account';
-
-const styles = stylex.create({
- resultDetail: {
- color: cssVar.colorTextTertiary,
- fontFamily: cssVar.fontFamilyCode,
- fontSize: 12,
- wordBreak: 'break-all',
- },
-});
-
-/**
- * Error body of a result banner: one readable sentence, with the raw platform
- * message folded behind a "show details" toggle so it stays available for
- * diagnosis without being dumped into the banner.
- */
-const ResultDetail = memo<{ detail?: string; hint: string }>(({ detail, hint }) => {
- const { t } = useTranslation('agent');
- const [open, setOpen] = useState(false);
- if (!detail || detail === hint) return <>{hint}</>;
- return (
- <Flexbox align={'flex-start'} gap={4}>
- <span>{hint}</span>
- <Button size={'small'} type={'text'} onClick={() => setOpen((value) => !value)}>
- {open ? t('channel.resultDetail.hide') : t('channel.resultDetail.show')}
- </Button>
- {open && <span {...stylex.props(styles.resultDetail)}>{detail}</span>}
- </Flexbox>
- );
-});
-
-ResultDetail.displayName = 'ResultDetail';
-
-interface StatusAlertsProps {
- connectResult?: TestResult;
- currentConfig?: CurrentConfig;
- form: FormInstance<ChannelFormValues>;
- hasConfig: boolean;
- platformDef: SerializedPlatformDefinition;
- ref?: Ref<HTMLDivElement>;
- saveResult?: TestResult;
- testResult?: TestResult;
-}
-
-/**
- * Everything the operator has to act on, at the top of the page: a failed save,
- * the bot's connection outcome, a test result, and setup still missing.
- * Success of a plain save is a toast, not a banner.
- */
-const StatusAlerts = memo<StatusAlertsProps>(
- ({ connectResult, currentConfig, form, hasConfig, platformDef, ref, saveResult, testResult }) => {
- const { t } = useTranslation('agent');
- const platformId = platformDef.id;
-
- const settingsConnectionMode = useWatch(form, 'settings.connectionMode');
- const showWebhookUrl = platformDef.showWebhookUrl || settingsConnectionMode === 'webhook';
-
- // Strong reminder when an already-saved bot is missing the operator's
- // User ID. Without it, AI tools can't push notifications back to the
- // operator and the pairing approver identity is undefined. Skipped on
- // first-time config and on platforms whose schema doesn't expose
- // `userId` (e.g. WeChat, which auto-manages identity via QR).
- const hasUserIdField = useMemo(() => {
- const settings = platformDef.schema.find((f) => f.key === 'settings');
- return settings?.properties?.some((f) => f.key === 'userId') ?? false;
- }, [platformDef.schema]);
- const watchedUserId = useWatch(form, 'settings.userId');
- // `useWatch` returns `undefined` until the form hydrates from the
- // parent's `initialValues`. Fall back to the saved value only during
- // that pre-hydration window so we don't flash the alert for every
- // saved bot. Once the form has reported a value, trust the watched
- // value — including `undefined`, so "Reset to Default" (which clears
- // settings.userId) correctly re-surfaces the alert.
- const savedUserId = currentConfig?.settings?.userId;
- const [formHydrated, setFormHydrated] = useState(false);
- useEffect(() => {
- if (watchedUserId !== undefined) setFormHydrated(true);
- }, [watchedUserId]);
- const effectiveUserId = formHydrated ? watchedUserId : savedUserId;
- const userIdMissing =
- hasConfig &&
- hasUserIdField &&
- !(typeof effectiveUserId === 'string' && effectiveUserId.trim());
-
- const webhookMigration =
- hasConfig && showWebhookUrl
- ? platformId === 'qq'
- ? 'qq'
- : platformId === 'slack'
- ? 'slack'
- : platformId === 'feishu' || platformId === 'lark'
- ? 'feishu'
- : undefined
- : undefined;
-
- const showSaveError = saveResult?.type === 'error';
- if (!showSaveError && !connectResult && !testResult && !userIdMissing && !webhookMigration)
- return null;
-
- return (
- <Flexbox gap={12} ref={ref} style={{ width: '100%' }}>
- {showSaveError && (
- <Alert
- closable
- showIcon
- title={t('channel.saveFailed')}
- type={'error'}
- description={
- <ResultDetail
- detail={saveResult.errorDetail}
- hint={saveResult.hint || t('channel.saveFailedHint')}
- />
- }
- />
- )}
-
- {connectResult && (
- <Alert
- closable
- showIcon
- type={connectResult.type}
- description={
- connectResult.type === 'error' ? (
- <ResultDetail
- detail={connectResult.errorDetail}
- hint={connectResult.hint || t('channel.connectFailedHint')}
- />
- ) : undefined
- }
- title={
- connectResult.title ||
- (connectResult.type === 'success'
- ? t('channel.connectSuccess')
- : t('channel.connectFailed'))
- }
- />
- )}
-
- {testResult && (
- <Alert
- closable
- showIcon
- type={testResult.type}
- description={
- testResult.type === 'error' ? (
- <ResultDetail
- detail={testResult.errorDetail}
- hint={testResult.hint || t('channel.testFailedHint')}
- />
- ) : undefined
- }
- title={
- testResult.type === 'success' ? t('channel.testSuccess') : t('channel.testFailed')
- }
- />
- )}
-
- {userIdMissing && (
- <Alert
- showIcon
- description={t('channel.userIdMissingHint')}
- title={t('channel.userIdMissingTitle')}
- type="info"
- action={
- <Button
- size={'small'}
- onClick={() =>
- document
- .getElementById(ACCOUNT_SECTION_ID)
- ?.scrollIntoView({ behavior: 'smooth', block: 'start' })
- }
- >
- {t('channel.userIdMissingAction')}
- </Button>
- }
- />
- )}
-
- {webhookMigration && (
- <Alert
- closable
- showIcon
- description={t(`channel.${webhookMigration}.webhookMigrationDesc`)}
- title={t(`channel.${webhookMigration}.webhookMigrationTitle`)}
- type="info"
- />
- )}
- </Flexbox>
- );
- },
-);
-
-StatusAlerts.displayName = 'ChannelStatusAlerts';
-
-export default StatusAlerts;
diff --git a/src/features/AgentChannel/PlatformDetail/WebhookUrlField.tsx b/src/features/AgentChannel/PlatformDetail/WebhookUrlField.tsx
deleted file mode 100644
index f8d7e1fce4c..00000000000
--- a/src/features/AgentChannel/PlatformDetail/WebhookUrlField.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-'use client';
-
-import { Button, cssVar, Flexbox, Input, toast } from '@lobehub/ui';
-import { Form, type FormInstance, useWatch } from '@lobehub/ui/form';
-import { Copy } from 'lucide-react';
-import { memo } from 'react';
-import { Trans, useTranslation } from 'react-i18next';
-
-import { useAppOrigin } from '@/hooks/useAppOrigin';
-import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
-
-import type { ChannelFormValues } from './index';
-import { CHANNEL_INPUT_MIN_WIDTH } from './SchemaField';
-
-interface WebhookUrlFieldProps {
- form: FormInstance<ChannelFormValues>;
- platformDef: SerializedPlatformDefinition;
-}
-
-/**
- * The URL the platform must call, shown in the connection card next to the
- * credentials it belongs with. Only webhook-mode platforms need it.
- */
-const WebhookUrlField = memo<WebhookUrlFieldProps>(({ form, platformDef }) => {
- const { t } = useTranslation('agent');
- const origin = useAppOrigin();
- const applicationId = useWatch(form, 'applicationId');
- const connectionMode = useWatch(form, 'settings.connectionMode');
-
- if (!platformDef.showWebhookUrl && connectionMode !== 'webhook') return null;
-
- const webhookUrl = applicationId
- ? `${origin}/api/agent/webhooks/${platformDef.id}/${applicationId}`
- : `${origin}/api/agent/webhooks/${platformDef.id}`;
-
- const handleCopy = async () => {
- await navigator.clipboard.writeText(webhookUrl);
- toast.success(t('channel.copied'));
- };
-
- return (
- <Form.Field
- divider
- label={t('channel.endpointUrl')}
- minWidth={CHANNEL_INPUT_MIN_WIDTH}
- desc={
- <Trans<'channel.endpointUrlHint', 'agent'>
- components={{ bold: <strong /> }}
- i18nKey="channel.endpointUrlHint"
- ns="agent"
- values={{ fieldName: 'Event Subscription URL', name: platformDef.name }}
- />
- }
- >
- <Flexbox horizontal gap={8} style={{ width: '100%' }}>
- <Input readOnly style={{ flex: 1, fontFamily: cssVar.fontFamilyCode }} value={webhookUrl} />
- <Button icon={<Copy size={14} />} onClick={handleCopy}>
- {t('channel.copy')}
- </Button>
- </Flexbox>
- </Form.Field>
- );
-});
-
-WebhookUrlField.displayName = 'ChannelWebhookUrlField';
-
-export default WebhookUrlField;
diff --git a/src/features/AgentChannel/PlatformDetail/accessStance.test.ts b/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
new file mode 100644
index 00000000000..48afd4f75a1
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/accessStance.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ accessIssues,
+ applyDmStance,
+ countListed,
+ deriveDmStance,
+ dropHiddenIncompleteRows,
+} from './accessStance';
+
+const listed = [{ id: '1' }, { id: ' ' }, { id: '2', name: 'Ada' }];
+
+describe('countListed', () => {
+ it('counts only rows that carry an ID', () => {
+ expect(countListed(listed)).toBe(2);
+ expect(countListed(undefined)).toBe(0);
+ expect(countListed('1,2')).toBe(0);
+ });
+});
+
+describe('deriveDmStance', () => {
+ it.each([
+ [{ dmPolicy: 'pairing' }, 'approval'],
+ [{ dmPolicy: 'disabled' }, 'closed'],
+ [{ dmPolicy: 'allowlist' }, 'listed'],
+ [{ dmPolicy: 'open', allowFrom: [] }, 'everyone'],
+ [{}, 'everyone'],
+ ])('reads %j as %s', (settings, stance) => {
+ expect(deriveDmStance(settings)).toBe(stance);
+ });
+
+ it('reads an open policy with a filled list as listed people only, because the list gates everyone', () => {
+ expect(deriveDmStance({ allowFrom: listed, dmPolicy: 'open' })).toBe('listed');
+ });
+
+ it('keeps pairing and closed even when a list exists', () => {
+ expect(deriveDmStance({ allowFrom: listed, dmPolicy: 'pairing' })).toBe('approval');
+ expect(deriveDmStance({ allowFrom: listed, dmPolicy: 'disabled' })).toBe('closed');
+ });
+});
+
+describe('applyDmStance', () => {
+ it('sets only the policy for approval, listed and closed, and keeps the list', () => {
+ expect(applyDmStance('approval', { allowFrom: listed })).toEqual({
+ dropped: 0,
+ patch: { dmPolicy: 'pairing' },
+ });
+ expect(applyDmStance('listed', {}).patch).toEqual({ dmPolicy: 'allowlist' });
+ expect(applyDmStance('closed', {}).patch).toEqual({ dmPolicy: 'disabled' });
+ });
+
+ it('clears the list for everyone and says how many people that drops', () => {
+ expect(applyDmStance('everyone', { allowFrom: listed })).toEqual({
+ dropped: 2,
+ patch: { allowFrom: [], dmPolicy: 'open' },
+ });
+ expect(applyDmStance('everyone', {}).dropped).toBe(0);
+ });
+
+ it('round-trips: the stance applied is the stance read back', () => {
+ for (const stance of ['approval', 'closed', 'everyone', 'listed'] as const) {
+ const { patch } = applyDmStance(stance, { allowFrom: listed });
+ const next = { allowFrom: patch.allowFrom ?? listed, dmPolicy: patch.dmPolicy };
+ expect(deriveDmStance(next)).toBe(stance);
+ }
+ });
+});
+
+describe('accessIssues', () => {
+ it('flags pairing without an owner ID, which the server refuses to save', () => {
+ expect(accessIssues({ dmPolicy: 'pairing' })).toEqual(['approverMissing']);
+ expect(accessIssues({ dmPolicy: 'pairing', userId: ' 88 ' })).toEqual([]);
+ });
+
+ it('flags empty lists that fail closed', () => {
+ expect(accessIssues({ dmPolicy: 'allowlist', userId: '1' })).toEqual(['listEmpty']);
+ expect(accessIssues({ groupAllowFrom: [], groupPolicy: 'allowlist' })).toEqual([
+ 'groupListEmpty',
+ ]);
+ });
+
+ it('is quiet for the default setup', () => {
+ expect(accessIssues({ dmPolicy: 'open', groupPolicy: 'open' })).toEqual([]);
+ });
+});
+
+describe('dropHiddenIncompleteRows', () => {
+ it('drops a half-added group row once groups are no longer limited to a list', () => {
+ expect(
+ dropHiddenIncompleteRows({
+ groupAllowFrom: [{ id: '42' }, { id: '' }],
+ groupPolicy: 'open',
+ }),
+ ).toEqual({ groupAllowFrom: [{ id: '42' }] });
+ });
+
+ it('keeps an incomplete group row while the group list is still shown', () => {
+ expect(
+ dropHiddenIncompleteRows({ groupAllowFrom: [{ id: '' }], groupPolicy: 'allowlist' }),
+ ).toEqual({});
+ });
+
+ it('drops a half-added person row when the people list is hidden', () => {
+ expect(dropHiddenIncompleteRows({ allowFrom: [{ id: ' ' }], dmPolicy: 'disabled' })).toEqual({
+ allowFrom: [],
+ });
+ });
+
+ it('leaves the people list alone while it is shown', () => {
+ expect(dropHiddenIncompleteRows({ allowFrom: [{ id: '' }], dmPolicy: 'pairing' })).toEqual({});
+ expect(
+ dropHiddenIncompleteRows({ allowFrom: [{ id: '7' }, { id: '' }], dmPolicy: 'disabled' }),
+ ).toEqual({});
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/accessStance.ts b/src/features/AgentChannel/PlatformDetail/accessStance.ts
new file mode 100644
index 00000000000..ee4ef87c743
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/accessStance.ts
@@ -0,0 +1,129 @@
+/**
+ * The page asks people one question — "who can DM it?" — while the runtime
+ * answers it with three settings (`dmPolicy`, the global `allowFrom` list and
+ * the owner's `userId`). These helpers translate between the two without
+ * pretending they are the same thing:
+ *
+ * - A non-empty `allowFrom` restricts everyone, in DMs and in groups, whatever
+ * `dmPolicy` says. So "everyone" is only true when the list is empty, and a
+ * stored `open` policy with a filled list reads as "listed people only".
+ * - `pairing` is the one policy that lets strangers through to a pairing code
+ * first, and it needs the owner's `userId` to approve them.
+ */
+
+export type DmStance = 'approval' | 'closed' | 'everyone' | 'listed';
+
+export interface StanceSettings {
+ allowFrom?: unknown;
+ dmPolicy?: string;
+}
+
+/** How many usable rows (with an ID) a list holds. */
+export const countListed = (list: unknown): number =>
+ Array.isArray(list)
+ ? list.filter(
+ (entry) =>
+ entry &&
+ typeof entry === 'object' &&
+ String((entry as { id?: unknown }).id ?? '').trim() !== '',
+ ).length
+ : 0;
+
+export const deriveDmStance = ({ allowFrom, dmPolicy }: StanceSettings): DmStance => {
+ switch (dmPolicy) {
+ case 'pairing': {
+ return 'approval';
+ }
+ case 'disabled': {
+ return 'closed';
+ }
+ case 'allowlist': {
+ return 'listed';
+ }
+ default: {
+ return countListed(allowFrom) > 0 ? 'listed' : 'everyone';
+ }
+ }
+};
+
+export interface StanceChange {
+ /** People who would fall off the list by applying the stance. */
+ dropped: number;
+ patch: { allowFrom?: never[]; dmPolicy: 'allowlist' | 'disabled' | 'open' | 'pairing' };
+}
+
+/**
+ * The form changes that make `stance` true. Only "everyone" touches the list,
+ * because a filled list would otherwise keep restricting everyone.
+ */
+export const applyDmStance = (stance: DmStance, settings: StanceSettings): StanceChange => {
+ switch (stance) {
+ case 'approval': {
+ return { dropped: 0, patch: { dmPolicy: 'pairing' } };
+ }
+ case 'closed': {
+ return { dropped: 0, patch: { dmPolicy: 'disabled' } };
+ }
+ case 'listed': {
+ return { dropped: 0, patch: { dmPolicy: 'allowlist' } };
+ }
+ default: {
+ return {
+ dropped: countListed(settings.allowFrom),
+ patch: { allowFrom: [], dmPolicy: 'open' },
+ };
+ }
+ }
+};
+
+export type AccessIssue = 'approverMissing' | 'groupListEmpty' | 'listEmpty';
+
+export interface AccessSettings extends StanceSettings {
+ groupAllowFrom?: unknown;
+ groupPolicy?: string;
+ userId?: unknown;
+}
+
+/** Things that leave the current choice not working the way it reads. */
+export const accessIssues = (settings: AccessSettings): AccessIssue[] => {
+ const issues: AccessIssue[] = [];
+ const userId = typeof settings.userId === 'string' ? settings.userId.trim() : '';
+
+ if (settings.dmPolicy === 'pairing' && !userId) issues.push('approverMissing');
+ if (settings.dmPolicy === 'allowlist' && countListed(settings.allowFrom) === 0)
+ issues.push('listEmpty');
+ if (settings.groupPolicy === 'allowlist' && countListed(settings.groupAllowFrom) === 0)
+ issues.push('groupListEmpty');
+
+ return issues;
+};
+
+const hasId = (entry: unknown) =>
+ typeof entry === 'string'
+ ? entry.trim() !== ''
+ : !!entry &&
+ typeof entry === 'object' &&
+ String((entry as { id?: unknown }).id ?? '').trim() !== '';
+
+/**
+ * Rows without an ID in a list the page has just hidden. A hidden list stays mounted (so a saved
+ * list is never dropped), which also keeps its "ID required" check alive: a half-added row would
+ * block every save with an error nobody can see. Returns only the lists that changed.
+ */
+export const dropHiddenIncompleteRows = (
+ settings: AccessSettings & { groupAllowFrom?: unknown; groupPolicy?: string },
+): Record<string, unknown> => {
+ const patch: Record<string, unknown> = {};
+ const prune = (key: 'allowFrom' | 'groupAllowFrom') => {
+ const list = settings[key];
+ if (Array.isArray(list) && list.some((entry) => !hasId(entry))) patch[key] = list.filter(hasId);
+ };
+
+ const stance = deriveDmStance(settings);
+ const peopleListShown =
+ stance === 'approval' || stance === 'listed' || countListed(settings.allowFrom) > 0;
+ if (!peopleListShown) prune('allowFrom');
+ if (settings.groupPolicy !== 'allowlist') prune('groupAllowFrom');
+
+ return patch;
+};
diff --git a/src/features/AgentChannel/PlatformDetail/buildRules.test.ts b/src/features/AgentChannel/PlatformDetail/buildRules.test.ts
index 302359d7c49..0fad5570dd8 100644
--- a/src/features/AgentChannel/PlatformDetail/buildRules.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/buildRules.test.ts
@@ -1,7 +1,7 @@
import { BOT_CREDENTIAL_MASK } from '@lobechat/const';
import { describe, expect, it } from 'vitest';
-import { buildValidate } from './Body';
+import { buildValidate } from './SchemaField';
/** Discord's real bot-token pattern, the one a masked value has to survive. */
const tokenField = {
diff --git a/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts b/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts
new file mode 100644
index 00000000000..f2720ff8c9e
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/channelTabs.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FieldSchema } from '@/server/services/bot/platforms/types';
+
+import { defaultTab, footerSaveHidden, resolveTabs, tabsWithIssues } from './channelTabs';
+
+const schema: FieldSchema[] = [
+ { key: 'applicationId', label: 'id', required: true, type: 'string' },
+ {
+ key: 'credentials',
+ label: 'credentials',
+ properties: [
+ { key: 'botToken', label: 'token', required: true, type: 'password' },
+ { key: 'note', label: 'note', type: 'string' },
+ ],
+ type: 'object',
+ },
+];
+
+describe('resolveTabs', () => {
+ it('always has connect, then the settings tabs the platform has, in page order', () => {
+ expect(resolveTabs(['advanced', 'reply', 'wake', 'access'])).toEqual([
+ 'connect',
+ 'access',
+ 'wake',
+ 'reply',
+ 'advanced',
+ ]);
+ expect(resolveTabs(['reply'])).toEqual(['connect', 'reply']);
+ expect(resolveTabs([])).toEqual(['connect']);
+ });
+});
+
+describe('defaultTab', () => {
+ it('starts a new channel on connect', () => {
+ expect(defaultTab(['connect', 'access', 'reply'], false)).toBe('connect');
+ });
+
+ it('opens a saved channel on its first settings tab', () => {
+ expect(defaultTab(['connect', 'access', 'reply'], true)).toBe('access');
+ expect(defaultTab(['connect', 'reply'], true)).toBe('reply');
+ });
+
+ it('stays on connect when there is nothing else', () => {
+ expect(defaultTab(['connect'], true)).toBe('connect');
+ });
+});
+
+describe('tabsWithIssues', () => {
+ it('flags connect while a required credential or the app ID is empty', () => {
+ expect(tabsWithIssues({}, schema)).toEqual(['connect']);
+ expect(tabsWithIssues({ applicationId: '1', credentials: { botToken: ' ' } }, schema)).toEqual([
+ 'connect',
+ ]);
+ expect(tabsWithIssues({ credentials: { botToken: 't' } }, schema)).toEqual(['connect']);
+ });
+
+ it('is quiet once required values are there, including a stored masked secret', () => {
+ expect(
+ tabsWithIssues({ applicationId: '1', credentials: { botToken: '••••' } }, schema),
+ ).toEqual([]);
+ });
+
+ it('flags access when approval is chosen without an owner ID', () => {
+ const values = {
+ applicationId: '1',
+ credentials: { botToken: 't' },
+ settings: { dmPolicy: 'pairing' },
+ };
+ expect(tabsWithIssues(values, schema)).toEqual(['access']);
+ expect(
+ tabsWithIssues({ ...values, settings: { ...values.settings, userId: '9' } }, schema),
+ ).toEqual([]);
+ });
+
+ it('lists several tabs in page order', () => {
+ expect(tabsWithIssues({ settings: { dmPolicy: 'pairing' } }, schema)).toEqual([
+ 'connect',
+ 'access',
+ ]);
+ });
+});
+
+describe('footerSaveHidden', () => {
+ it('leaves the save to the setup steps on the Connect tab of a new bot', () => {
+ expect(footerSaveHidden({ activeTab: 'connect', hasConfig: false, stepSave: true })).toBe(true);
+ });
+
+ it('keeps the bar save where no step offers it', () => {
+ // Another tab of a new bot: no step there.
+ expect(footerSaveHidden({ activeTab: 'access', hasConfig: false, stepSave: true })).toBe(false);
+ // A platform without setup steps (WeChat, iMessage).
+ expect(footerSaveHidden({ activeTab: 'connect', hasConfig: false, stepSave: false })).toBe(
+ false,
+ );
+ // A saved bot: the steps fold away and have no save step.
+ expect(footerSaveHidden({ activeTab: 'connect', hasConfig: true, stepSave: true })).toBe(false);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/channelTabs.ts b/src/features/AgentChannel/PlatformDetail/channelTabs.ts
new file mode 100644
index 00000000000..39873c775d1
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/channelTabs.ts
@@ -0,0 +1,66 @@
+import type { FieldSchema } from '@/server/services/bot/platforms/types';
+
+import { accessIssues } from './accessStance';
+import { getSchemaFields, type SettingsGroupKey } from './settingsGroups';
+
+/**
+ * The page is one tab per question a person asks, in the order they ask them:
+ * how is it connected, who may use it, when may it speak up unprompted, how does it reply, what else is there.
+ */
+export type ChannelTab = 'access' | 'advanced' | 'connect' | 'reply' | 'wake';
+
+export const TAB_ORDER: ChannelTab[] = ['connect', 'access', 'wake', 'reply', 'advanced'];
+
+/** Connecting always exists; the other tabs exist when the platform has settings for them. */
+export const resolveTabs = (settingsGroupKeys: SettingsGroupKey[]): ChannelTab[] =>
+ TAB_ORDER.filter((tab) => tab === 'connect' || settingsGroupKeys.includes(tab));
+
+/**
+ * A new channel starts on connecting, since nothing else works before it. A
+ * saved one opens on the first settings tab: the connection is done.
+ */
+export const defaultTab = (tabs: ChannelTab[], hasConfig: boolean): ChannelTab =>
+ (hasConfig ? tabs.find((tab) => tab !== 'connect') : undefined) ?? 'connect';
+
+export interface ChannelValues {
+ applicationId?: string;
+ credentials?: Record<string, string>;
+ settings?: Record<string, unknown>;
+}
+
+const isFilled = (value: unknown) => typeof value === 'string' && value.trim() !== '';
+
+/**
+ * Tabs that hold something the person still has to fix, in tab order. A
+ * credential that is stored (masked) counts as filled.
+ */
+export const tabsWithIssues = (values: ChannelValues, schema: FieldSchema[]): ChannelTab[] => {
+ const issues = new Set<ChannelTab>();
+
+ const applicationId = schema.find((field) => field.key === 'applicationId');
+ const missingCredential = getSchemaFields(schema, 'credentials').some(
+ (field) => field.required && !isFilled(values.credentials?.[field.key]),
+ );
+ if ((applicationId?.required && !isFilled(values.applicationId)) || missingCredential)
+ issues.add('connect');
+
+ if (accessIssues(values.settings ?? {}).includes('approverMissing')) issues.add('access');
+
+ return TAB_ORDER.filter((tab) => issues.has(tab));
+};
+
+/**
+ * Whether the bottom bar leaves out its Save button. While a bot is being set up, the Connect
+ * tab's steps end with a "Save and connect" step of their own; the bar repeating it below reads as
+ * a second, different action. Other tabs have no such step, so the bar keeps it there.
+ */
+export const footerSaveHidden = ({
+ activeTab,
+ hasConfig,
+ stepSave,
+}: {
+ activeTab: ChannelTab;
+ hasConfig: boolean;
+ /** The platform's setup steps include the save step. */
+ stepSave: boolean;
+}): boolean => !hasConfig && stepSave && activeTab === 'connect';
diff --git a/src/features/AgentChannel/PlatformDetail/formState.test.ts b/src/features/AgentChannel/PlatformDetail/formState.test.ts
index 18f7657ebea..d9b78a46323 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.test.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.test.ts
@@ -8,9 +8,11 @@ import {
findOverLimitSettings,
getChannelFormValues,
isFieldReleased,
+ isWakeMasterReleased,
mergeCredentialsForSave,
mergeSettingsWithDefaults,
shouldAdoptIncomingConfig,
+ withWakeMasterOn,
} from './formState';
const slackSchema: FieldSchema[] = [
@@ -323,3 +325,43 @@ describe('findOverLimitSettings', () => {
expect(findOverLimitSettings(undefined, { allowChannels: [{ id: '1' }] })).toEqual([]);
});
});
+
+describe('bot-wake master switch', () => {
+ const schema = [
+ {
+ key: 'settings',
+ label: 'settings',
+ properties: [
+ {
+ default: false,
+ featureFlag: 'enableBotWake',
+ key: 'botWakeEnabled',
+ label: 'x',
+ type: 'boolean',
+ },
+ { key: 'charLimit', label: 'y', type: 'number' },
+ ],
+ type: 'object',
+ },
+ ] as FieldSchema[];
+
+ it('is released only when the rollout flag is on', () => {
+ expect(isWakeMasterReleased(schema, { enableBotWake: true })).toBe(true);
+ expect(isWakeMasterReleased(schema, { enableBotWake: false })).toBe(false);
+ expect(isWakeMasterReleased(schema, undefined)).toBe(false);
+ expect(isWakeMasterReleased([], { enableBotWake: true })).toBe(false);
+ });
+
+ it('is switched on in the form for a released user, whatever was stored', () => {
+ expect(withWakeMasterOn({ botWakeEnabled: false, charLimit: 2000 }, true)).toEqual({
+ botWakeEnabled: true,
+ charLimit: 2000,
+ });
+ });
+
+ it('is left alone for everyone else, so saving a bot never switches the options on for them', () => {
+ const settings = { botWakeEnabled: false };
+
+ expect(withWakeMasterOn(settings, false)).toBe(settings);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/formState.ts b/src/features/AgentChannel/PlatformDetail/formState.ts
index 5f9ec7ba5e1..49cc11b9b33 100644
--- a/src/features/AgentChannel/PlatformDetail/formState.ts
+++ b/src/features/AgentChannel/PlatformDetail/formState.ts
@@ -198,3 +198,26 @@ export const isFieldReleased = (
field: Pick<FieldSchema, 'featureFlag'>,
featureFlags: Record<string, unknown> | undefined,
): boolean => !field.featureFlag || featureFlags?.[field.featureFlag] === true;
+
+/** The master switch of the bot-wake options. The page no longer asks: once the options are released, they are on. */
+export const WAKE_MASTER_KEY = 'botWakeEnabled';
+
+/** Whether the bot-wake options (and so their master switch) are released to the signed-in user. */
+export const isWakeMasterReleased = (
+ schema: FieldSchema[] | undefined,
+ featureFlags: Record<string, unknown> | undefined,
+): boolean => {
+ const fields = schema?.find((field) => field.key === 'settings')?.properties ?? [];
+ const master = fields.find((field) => field.key === WAKE_MASTER_KEY);
+ return !!master?.featureFlag && isFieldReleased(master, featureFlags);
+};
+
+/**
+ * Settings for the form with the bot-wake master switch on, for a user the options are released
+ * to. Anyone else keeps the stored value, so a bot the options were never shown for is not
+ * switched on by saving it.
+ */
+export const withWakeMasterOn = <T extends Record<string, unknown>>(
+ settings: T,
+ released: boolean,
+): T => (released ? { ...settings, [WAKE_MASTER_KEY]: true } : settings);
diff --git a/src/features/AgentChannel/PlatformDetail/heroModel.test.ts b/src/features/AgentChannel/PlatformDetail/heroModel.test.ts
new file mode 100644
index 00000000000..d332899c023
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/heroModel.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+
+import { getSetupGuide } from '../quickSetup/guides';
+import { findInviteLink, maskId } from './heroModel';
+
+describe('maskId', () => {
+ it('keeps short IDs and abbreviates long ones', () => {
+ expect(maskId('cli_a8f2c91b')).toBe('cli_a8f2c91b');
+ expect(maskId('1294857201938475610')).toBe('1294…5610');
+ expect(maskId(' ')).toBe('');
+ expect(maskId(undefined)).toBe('');
+ });
+});
+
+describe('findInviteLink', () => {
+ it('finds Discord’s invite link once the app ID is known', () => {
+ const guide = getSetupGuide('discord', {
+ appName: 'Lobe',
+ applicationId: '1294857201938475610',
+ });
+ expect(findInviteLink(guide)?.href).toContain('1294857201938475610');
+ });
+
+ it('has none before the app ID, or on platforms without an invite step', () => {
+ expect(findInviteLink(getSetupGuide('discord', { appName: 'Lobe' }))).toBeUndefined();
+ expect(findInviteLink(getSetupGuide('feishu', { appName: 'Lobe' }))).toBeUndefined();
+ expect(findInviteLink(undefined)).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/heroModel.ts b/src/features/AgentChannel/PlatformDetail/heroModel.ts
new file mode 100644
index 00000000000..f421de57a3b
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/heroModel.ts
@@ -0,0 +1,11 @@
+import type { SetupGuide } from '../quickSetup/guides';
+
+/** Shows enough of an ID to recognise it without printing all of it. */
+export const maskId = (id?: string): string => {
+ const value = id?.trim() ?? '';
+ return value.length > 12 ? `${value.slice(0, 4)}…${value.slice(-4)}` : value;
+};
+
+/** The "invite the bot" link a platform's setup guide knows, once the app ID is known. */
+export const findInviteLink = (guide?: SetupGuide): { href: string } | undefined =>
+ guide?.steps.find((step) => step.link?.label === 'inviteBot')?.link;
diff --git a/src/features/AgentChannel/PlatformDetail/index.tsx b/src/features/AgentChannel/PlatformDetail/index.tsx
index 9e4d5392696..f295626ced3 100644
--- a/src/features/AgentChannel/PlatformDetail/index.tsx
+++ b/src/features/AgentChannel/PlatformDetail/index.tsx
@@ -1,17 +1,18 @@
'use client';
import {
+ ActionIcon,
Alert,
Button,
confirmModal,
createStaticStyles,
+ Drawer,
Flexbox,
- responsive,
- Text,
+ Icon,
toast,
} from '@lobehub/ui';
-import { useForm } from '@lobehub/ui/form';
-import { ExternalLink, RefreshCw } from 'lucide-react';
+import { useForm, useWatch } from '@lobehub/ui/form';
+import { ExternalLink, PanelRightClose, PanelRightOpen } from 'lucide-react';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -23,66 +24,108 @@ import type { SerializedPlatformDefinition } from '@/server/services/bot/platfor
import { agentBotProviderService } from '@/services/agentBotProvider';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
+import { useServerConfigStore } from '@/store/serverConfig';
import { BOT_RUNTIME_STATUSES, type BotRuntimeStatusSnapshot } from '@/types/botRuntimeStatus';
-import { getPlatformIcon } from '../const';
+import { platformCredentialBodyMap } from '../platform/registry';
+import { getSetupGuide } from '../quickSetup/guides';
import { keepPendingConnectResult, toTestResult } from './actionResults';
import Body from './Body';
+import { ChannelHero } from './ChannelHero';
+import { ChannelTabBar } from './ChannelTabBar';
+import {
+ type ChannelTab,
+ defaultTab,
+ footerSaveHidden,
+ resolveTabs,
+ tabsWithIssues,
+} from './channelTabs';
+import { FooterActions, FooterNotices } from './Footer';
import {
findOverLimitSettings,
getChannelFormValues,
+ isWakeMasterReleased,
mergeCredentialsForSave,
mergeSettingsWithDefaults,
shouldAdoptIncomingConfig,
+ withWakeMasterOn,
} from './formState';
import { type ChannelPostSave, ChannelPostSaveContext } from './postSaveContext';
-import SaveBar from './SaveBar';
-import StatusAlerts from './StatusAlerts';
+import { QuickView } from './QuickView';
+import { hasPendingChanges, pickKeys, replyDiffers } from './replySettings';
+import { createSaveCoordinator } from './saveCoordinator';
+import { getSchemaFields, groupSettingsFields, REPLY_KEYS } from './settingsGroups';
+import { useNarrowLayout } from './useNarrowLayout';
const styles = createStaticStyles(({ css, cssVar }) => ({
content: css`
display: flex;
+ flex: 1;
flex-direction: column;
- gap: 24px;
align-items: center;
width: 100%;
- max-width: 1072px;
- margin-inline: auto;
- padding-block: 24px 32px;
padding-inline: 24px;
+ `,
+ // The page is one split from the top: the bot's header, tabs and form on the
+ // left, the chat preview fixed on the right behind a divider. Below this
+ // width there is no room for two columns, so the preview folds into a button
+ // that opens it from the right.
+ layout: css`
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 360px;
+ flex: 1;
+ gap: 0;
+ align-items: stretch;
- ${responsive.sm} {
- padding-inline: 16px;
- }
+ width: 100%;
- /* Let a long section description wrap instead of pushing past the card. */
- & .lobe-form-form__group-title,
- & .lobe-form-form__group-title > div {
- flex-shrink: 1;
- min-width: 0;
+ &[data-preview='closed'],
+ &[data-narrow='true'] {
+ grid-template-columns: minmax(0, 1fr);
}
`,
- intro: css`
- width: 100%;
- `,
- introIcon: css`
+ primary: css`
display: flex;
- flex: none;
+ grid-column: 1;
+ grid-row: 1;
+ flex-direction: column;
align-items: center;
- justify-content: center;
- width: 40px;
- height: 40px;
- border-radius: ${cssVar.borderRadiusLG};
+ min-width: 0;
+ padding-block: 16px 24px;
+ padding-inline-end: 32px;
- background: ${cssVar.colorFillTertiary};
+ &[data-preview='closed'],
+ &[data-narrow='true'] {
+ padding-inline-end: 0;
+ }
+ `,
+ hero: css`
+ width: 100%;
+ max-width: 1024px;
+ padding-block-end: 16px;
+ `,
+ tabs: css`
+ width: 100%;
+ max-width: 1024px;
+ `,
+ quickView: css`
+ grid-column: 2;
+ grid-row: 1;
+ padding-inline-start: 32px;
+ border-inline-start: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ quickViewSticky: css`
+ position: sticky;
+ inset-block-start: 0;
+ padding-block-start: 24px;
`,
main: css`
position: relative;
display: flex;
- flex: none;
+ flex: 1 0 auto;
flex-direction: column;
width: 100%;
@@ -97,14 +140,13 @@ const omitUndefinedValues = <T extends Record<string, unknown>>(record: T) =>
const getFormValues = (
schema: SerializedPlatformDefinition['schema'],
config?: CurrentConfig,
+ wakeReleased = false,
): ChannelFormValues => {
const values = config ? getChannelFormValues(config) : { credentials: {}, settings: {} };
+ const settings = mergeSettingsWithDefaults(schema, omitUndefinedValues(values.settings));
return {
...values,
- settings: mergeSettingsWithDefaults(schema, omitUndefinedValues(values.settings)) as Record<
- string,
- {} | undefined
- >,
+ settings: withWakeMasterOn(settings, wakeReleased) as Record<string, {} | undefined>,
};
};
@@ -144,12 +186,74 @@ const PlatformDetail = memo<PlatformDetailProps>(
const { t } = useTranslation('agent');
const navigate = useWorkspaceAwareNavigate();
const agentName = useAgentStore((s) => agentSelectors.getAgentMetaById(agentId)(s).title);
+ const agentAvatar = useAgentStore((s) => agentSelectors.getAgentMetaById(agentId)(s).avatar);
+ const agentBackground = useAgentStore(
+ (s) => agentSelectors.getAgentMetaById(agentId)(s).backgroundColor,
+ );
+
+ // Options behind a rollout flag are left out of the tabs until the flag is on.
+ const featureFlags = useServerConfigStore((state) => state.featureFlags) as
+ Record<string, unknown> | undefined;
+ const wakeReleased = isWakeMasterReleased(platformDef.schema, featureFlags);
+ // What is stored, in form shape. The reply settings are compared against it
+ // to decide what to save on the spot, everything else to decide what still
+ // waits for the Save button.
+ const storedValues = useMemo(
+ () => getFormValues(platformDef.schema, currentConfig, wakeReleased),
+ [platformDef.schema, currentConfig, wakeReleased],
+ );
+ const storedRef = useRef(storedValues);
+ useEffect(() => {
+ storedRef.current = storedValues;
+ }, [storedValues]);
+ // The chat preview sits beside the form while there is room, and can be
+ // folded away; on a narrow window it opens from the right instead.
+ const narrow = useNarrowLayout();
+ const [previewOpen, setPreviewOpen] = useState(true);
+ const [drawerOpen, setDrawerOpen] = useState(false);
+ const previewInline = !narrow && previewOpen;
+ const replyKeys = useMemo(
+ () =>
+ REPLY_KEYS.filter((key) =>
+ getSchemaFields(platformDef.schema, 'settings').some((field) => field.key === key),
+ ),
+ [platformDef.schema],
+ );
+ const valuesChangedRef = useRef<() => void>(undefined);
+ const autoSavingRef = useRef(false);
+ // Reply autosaves and the Save button both write the whole settings column;
+ // this keeps them from overlapping (see `createSaveCoordinator`).
+ const saveCoordinator = useMemo(() => createSaveCoordinator(), []);
const [isDirty, setIsDirty] = useState(false);
const form = useForm<ChannelFormValues>({
- initialValues: getFormValues(platformDef.schema, currentConfig),
- onValuesChange: () => setIsDirty(true),
+ initialValues: getFormValues(platformDef.schema, currentConfig, wakeReleased),
+ onValuesChange: () => valuesChangedRef.current?.(),
});
+
+ // Which tab is open. `undefined` means nobody picked one, so the page picks:
+ // connecting for a new channel, the first settings tab once it is saved.
+ const [pickedTab, setPickedTab] = useState<ChannelTab>();
+ const tabs = useMemo(
+ () =>
+ resolveTabs(
+ groupSettingsFields(getSchemaFields(platformDef.schema, 'settings', featureFlags)).map(
+ (group) => group.key,
+ ),
+ ),
+ [featureFlags, platformDef.schema],
+ );
+ const activeTab =
+ pickedTab && tabs.includes(pickedTab) ? pickedTab : defaultTab(tabs, !!currentConfig);
+ const watchedValues = useWatch(form, (values) => values);
+ // The open tab already shows its own problems; the dot is for the others.
+ const tabIssues = useMemo(
+ () =>
+ watchedValues
+ ? tabsWithIssues(watchedValues, platformDef.schema).filter((tab) => tab !== activeTab)
+ : [],
+ [activeTab, platformDef.schema, watchedValues],
+ );
const { allowed: canEdit } = usePermission('edit_own_content');
const activeWorkspaceId = useActiveWorkspaceId();
const readOnly = disabled || !canEdit;
@@ -258,13 +362,13 @@ const PlatformDetail = memo<PlatformDetailProps>(
);
const connectResult = connectNotice ?? (runtimeHidden ? undefined : runtimeResult);
- // Failures from an explicit save, connect or test render in the alerts at the
- // top of the page; bring them into view, since the sticky Save button may have
- // been clicked from a section far below. Live runtime updates do not scroll.
- const alertsRef = useRef<HTMLDivElement>(null);
+ // Failures from an explicit save, connect or test show in the notices at the
+ // top of the form; bring them into view, since Save may have been clicked far
+ // below (the last setup step, the bottom bar). Live runtime updates do not scroll.
+ const noticesRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if ([saveResult, connectNotice, testResult].some((result) => result?.type === 'error')) {
- alertsRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
+ noticesRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, [saveResult, connectNotice, testResult]);
@@ -295,6 +399,7 @@ const PlatformDetail = memo<PlatformDetailProps>(
// runtimeStatus — otherwise background status refreshes would wipe
// in-progress form edits and cancel the connect-status polling loop.
useEffect(() => {
+ setPickedTab(undefined);
setSaveResult(undefined);
setConnectNotice(undefined);
setRuntimeHidden(false);
@@ -314,17 +419,105 @@ const PlatformDetail = memo<PlatformDetailProps>(
previousConfigRef.current = currentConfig;
if (!shouldAdoptIncomingConfig(previous, currentConfig, isDirty)) return;
+ // A reply setting is being saved: the copy coming back may not have this
+ // person's latest toggle yet, and adopting it would flip the toggle back.
+ if (autoSavingRef.current) return;
- form.reset(getFormValues(platformDef.schema, currentConfig));
+ form.reset(getFormValues(platformDef.schema, currentConfig, wakeReleased));
setIsDirty(false);
- }, [currentConfig, form, platformDef.schema, isDirty]);
+ }, [currentConfig, wakeReleased, form, platformDef.schema, isDirty]);
+
+ // Reply settings are switches and choices whose effect is seen at once in
+ // the chat, so they are stored as soon as they change instead of waiting for
+ // the Save button. Only the reply keys are written, on top of what is stored:
+ // a half-finished edit on another tab is neither saved nor lost.
+ const saveReplySettings = useCallback(async () => {
+ if (!currentConfig || writeDisabled || replyKeys.length === 0) return;
+ if (autoSavingRef.current || saveCoordinator.isExplicit()) return;
+
+ const { valid } = await form.validate(replyKeys.map((key) => `settings.${key}` as const));
+ // The Save button may have started while this was validating; it writes these values too.
+ if (!valid || saveCoordinator.isExplicit()) return;
+
+ const values = form.getValues();
+ const stored = storedRef.current;
+ if (!replyDiffers(values.settings, stored.settings, replyKeys)) return;
+
+ await saveCoordinator.runAuto(async () => {
+ autoSavingRef.current = true;
+ try {
+ const settings = mergeSettingsWithDefaults(
+ platformDef.schema,
+ omitUndefinedValues({ ...stored.settings, ...pickKeys(values.settings, replyKeys) }),
+ );
+ await updateBotProvider(currentConfig.id, agentId, { settings });
+ storedRef.current = { ...stored, settings: settings as ChannelFormValues['settings'] };
+ toast.success(t('channel.saved'));
+ } catch {
+ toast.error(t('channel.updateFailed'));
+ form.setValues({
+ settings: {
+ ...form.getValues().settings,
+ ...(pickKeys(stored.settings, replyKeys) as ChannelFormValues['settings']),
+ },
+ });
+ } finally {
+ autoSavingRef.current = false;
+ // Anything toggled while this save was running still has to go out.
+ valuesChangedRef.current?.();
+ }
+ });
+ }, [
+ agentId,
+ currentConfig,
+ form,
+ platformDef.schema,
+ replyKeys,
+ saveCoordinator,
+ t,
+ updateBotProvider,
+ writeDisabled,
+ ]);
+
+ const handleValuesChange = useCallback(() => {
+ const values = form.getValues();
+ setIsDirty(hasPendingChanges(values, storedRef.current, replyKeys));
+
+ if (!currentConfig || writeDisabled || replyKeys.length === 0) return;
+ if (!replyDiffers(values.settings, storedRef.current.settings, replyKeys)) return;
+
+ saveCoordinator.scheduleAuto(saveReplySettings, 400);
+ }, [currentConfig, form, replyKeys, saveCoordinator, saveReplySettings, writeDisabled]);
+ useEffect(() => {
+ valuesChangedRef.current = handleValuesChange;
+ }, [handleValuesChange]);
+ useEffect(() => () => saveCoordinator.dispose(), [saveCoordinator]);
const handleSave = useCallback(async () => {
if (writeDisabled) return;
+ // This save writes the reply settings too: drop a pending autosave, wait
+ // for one already on its way, and keep new ones out until this is done.
+ await saveCoordinator.beginExplicit();
+
try {
const { valid } = await form.validate();
- if (!valid) return;
+ if (!valid) {
+ // The invalid field may be on a tab that is not open. Open the first tab
+ // that has one, from the field the form marked, else from what is missing.
+ const marked = document
+ .querySelector('[role="tabpanel"][id^="channel-panel-"] [data-invalid]')
+ ?.closest('[role="tabpanel"]')
+ ?.id.replace('channel-panel-', '') as ChannelTab | undefined;
+ const target =
+ marked && tabs.includes(marked)
+ ? marked
+ : tabsWithIssues(form.getValues(), platformDef.schema).find((tab) =>
+ tabs.includes(tab),
+ );
+ if (target) setPickedTab(target);
+ return;
+ }
const values = form.getValues();
setSaving(true);
@@ -388,9 +581,17 @@ const PlatformDetail = memo<PlatformDetailProps>(
// local BlueBubbles bridge) as part of the same save.
await postSaveRef.current?.({ applicationId });
+ // A later reply autosave builds on what is stored; make that this save
+ // right away rather than when the refreshed config arrives.
+ storedRef.current = {
+ ...values,
+ applicationId,
+ credentials,
+ settings: settings as ChannelFormValues['settings'],
+ };
setIsDirty(false);
setSaveResult({ type: 'success' });
- toast.success(t('channel.saved'));
+ setTimeout(() => setSaveResult(undefined), 3000);
setSaving(false);
// Auto-connect bot after save
@@ -399,6 +600,8 @@ const PlatformDetail = memo<PlatformDetailProps>(
console.error(e);
setSaveResult({ errorDetail: e?.message || String(e), type: 'error' });
setSaving(false);
+ } finally {
+ saveCoordinator.endExplicit();
}
}, [
agentId,
@@ -408,6 +611,8 @@ const PlatformDetail = memo<PlatformDetailProps>(
createBotProvider,
updateBotProvider,
connectCurrentBot,
+ saveCoordinator,
+ tabs,
writeDisabled,
t,
]);
@@ -486,19 +691,27 @@ const PlatformDetail = memo<PlatformDetailProps>(
confirmModal({
content: t('channel.deleteConfirmDesc'),
okButtonProps: { danger: true },
- okText: t('channel.removeChannel'),
onOk: async () => {
try {
await deleteBotProvider(currentConfig.id, agentId);
toast.success(t('channel.removed'));
- form.reset(getFormValues(platformDef.schema));
+ form.reset(getFormValues(platformDef.schema, undefined, wakeReleased));
} catch {
toast.error(t('channel.removeFailed'));
}
},
title: t('channel.removeChannel'),
});
- }, [readOnly, currentConfig, agentId, deleteBotProvider, t, form, platformDef.schema]);
+ }, [
+ readOnly,
+ currentConfig,
+ agentId,
+ deleteBotProvider,
+ t,
+ form,
+ platformDef.schema,
+ wakeReleased,
+ ]);
const handleTestConnection = useCallback(async () => {
if (writeDisabled) return;
@@ -534,15 +747,13 @@ const PlatformDetail = memo<PlatformDetailProps>(
}, [writeDisabled, currentConfig, connectResult, platformDef.id, testConnection, t]);
const handleDiscard = useCallback(() => {
- form.reset(getFormValues(platformDef.schema, currentConfig));
+ form.reset(getFormValues(platformDef.schema, currentConfig, wakeReleased));
setIsDirty(false);
setSaveResult(undefined);
setTestResult(undefined);
- }, [currentConfig, form, platformDef.schema]);
-
- const handleFormValuesChange = useCallback(() => setIsDirty(true), []);
+ }, [currentConfig, wakeReleased, form, platformDef.schema]);
- const PlatformIcon = getPlatformIcon(platformDef.id) ?? getPlatformIcon(platformDef.name);
+ const handleFormValuesChange = handleValuesChange;
const handlePaidFeatureUpgrade = useCallback(() => {
navigate('/settings/plans');
@@ -552,28 +763,10 @@ const PlatformDetail = memo<PlatformDetailProps>(
<ChannelPostSaveContext value={postSaveRegistry}>
<main className={styles.main}>
<div className={styles.content}>
- <Flexbox horizontal align={'center'} className={styles.intro} gap={12}>
- {PlatformIcon && (
- <div className={styles.introIcon}>
- <PlatformIcon size={24} />
- </div>
- )}
- <Flexbox gap={2} style={{ minWidth: 0 }}>
- <Text as={'h1'} fontSize={20} style={{ margin: 0 }} weight={600}>
- {platformDef.name}
- </Text>
- <Text type={'secondary'}>
- {t('channel.detailDesc', {
- agent: agentName || t('channel.detailDescAgentFallback'),
- name: platformDef.name,
- })}
- </Text>
- </Flexbox>
- </Flexbox>
{paidFeatureBlocked && (
<Alert
showIcon
- style={{ width: '100%' }}
+ style={{ marginBlockStart: 16, maxWidth: 1024, width: '100%' }}
type={paidFeatureMode === 'notice' ? 'warning' : 'info'}
description={t(`channel.paidFeature.${paidFeatureMode}.desc.${paidFeatureScope}`, {
name: platformDef.name,
@@ -597,52 +790,128 @@ const PlatformDetail = memo<PlatformDetailProps>(
}
/>
)}
- <StatusAlerts
- connectResult={connectResult}
- currentConfig={currentConfig}
- form={form}
- hasConfig={!!currentConfig}
- platformDef={platformDef}
- ref={alertsRef}
- saveResult={saveResult}
- testResult={testResult}
- />
- <Body
- currentConfig={currentConfig}
- disabled={writeDisabled}
- form={form}
- hasConfig={!!currentConfig}
- platformDef={platformDef}
- quickSetupAppName={agentName}
- quickSetupScope={agentId}
- removeDisabled={readOnly || saving || connecting}
- connectionExtra={
- currentConfig ? (
- <Button
- disabled={writeDisabled || saving || connecting}
- icon={<RefreshCw size={14} />}
- loading={testing}
- size={'small'}
- onClick={handleTestConnection}
- >
- {t('channel.testConnection')}
- </Button>
- ) : undefined
- }
- onAuthenticated={handleExternalAuth}
- onDelete={handleDelete}
- onValuesChange={handleFormValuesChange}
- />
+ <div
+ className={styles.layout}
+ data-narrow={narrow}
+ data-preview={previewInline ? 'open' : 'closed'}
+ >
+ <div
+ className={styles.primary}
+ data-narrow={narrow}
+ data-preview={previewInline ? 'open' : 'closed'}
+ >
+ <div className={styles.hero}>
+ <ChannelHero
+ applicationId={currentConfig?.applicationId}
+ botName={agentName}
+ platformDef={platformDef}
+ status={currentConfig?.enabled ? runtimeSnapshot?.status : undefined}
+ extra={
+ previewInline ? undefined : (
+ <Button
+ icon={<Icon icon={PanelRightOpen} />}
+ onClick={() => (narrow ? setDrawerOpen(true) : setPreviewOpen(true))}
+ >
+ {t('channel.quickView.open')}
+ </Button>
+ )
+ }
+ />
+ </div>
+ <div className={styles.tabs}>
+ <ChannelTabBar
+ active={activeTab}
+ issues={tabIssues}
+ tabs={tabs}
+ onChange={setPickedTab}
+ />
+ </div>
+ <div ref={noticesRef} style={{ scrollMarginBlockStart: 16 }} />
+ <FooterNotices
+ connectResult={connectResult}
+ currentConfig={currentConfig}
+ form={form}
+ hasConfig={!!currentConfig}
+ platformDef={platformDef}
+ saveResult={saveResult}
+ testResult={testResult}
+ />
+ <Body
+ activeTab={activeTab}
+ currentConfig={currentConfig}
+ disabled={writeDisabled}
+ form={form}
+ hasConfig={!!currentConfig}
+ platformDef={platformDef}
+ quickSetupAppName={agentName}
+ quickSetupScope={agentId}
+ saving={saving}
+ onAuthenticated={handleExternalAuth}
+ onSave={handleSave}
+ onValuesChange={handleFormValuesChange}
+ />
+ <FooterActions
+ connecting={connecting}
+ disabled={readOnly}
+ form={form}
+ hasConfig={!!currentConfig}
+ isDirty={isDirty}
+ platformDef={platformDef}
+ saving={saving}
+ testing={testing}
+ writeDisabled={writeDisabled}
+ hideSave={footerSaveHidden({
+ activeTab,
+ hasConfig: !!currentConfig,
+ // Platforms with their own credential body (WeChat, iMessage) have no steps.
+ stepSave:
+ !platformCredentialBodyMap[platformDef.id] &&
+ !!getSetupGuide(platformDef.id, { appName: '' }),
+ })}
+ onCopied={() => toast.success(t('channel.copied'))}
+ onDelete={handleDelete}
+ onDiscard={handleDiscard}
+ onSave={handleSave}
+ onTestConnection={handleTestConnection}
+ />
+ </div>
+ {previewInline && (
+ <aside className={styles.quickView}>
+ <div className={styles.quickViewSticky}>
+ <QuickView
+ botAvatar={{ avatar: agentAvatar, background: agentBackground }}
+ botName={agentName}
+ form={form}
+ platformDef={platformDef}
+ extra={
+ <ActionIcon
+ aria-label={t('channel.quickView.collapse')}
+ icon={PanelRightClose}
+ title={t('channel.quickView.collapse')}
+ onClick={() => setPreviewOpen(false)}
+ />
+ }
+ />
+ </div>
+ </aside>
+ )}
+ </div>
+ <Drawer
+ open={narrow && drawerOpen}
+ placement={'right'}
+ title={t('channel.quickView.title')}
+ width={'min(420px, 92vw)'}
+ onClose={() => setDrawerOpen(false)}
+ >
+ <QuickView
+ hideTitle
+ botAvatar={{ avatar: agentAvatar, background: agentBackground }}
+ botName={agentName}
+ form={form}
+ platformDef={platformDef}
+ />
+ </Drawer>
</div>
- <SaveBar
- connecting={connecting}
- hasConfig={!!currentConfig}
- isDirty={isDirty}
- saving={saving}
- writeDisabled={writeDisabled}
- onDiscard={handleDiscard}
- onSave={handleSave}
- />
</main>
</ChannelPostSaveContext>
);
diff --git a/src/features/AgentChannel/PlatformDetail/previewModel.test.ts b/src/features/AgentChannel/PlatformDetail/previewModel.test.ts
new file mode 100644
index 00000000000..576b795bf37
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/previewModel.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+
+import { pickKeywords, resolveDmOutcome, resolveGroupOutcome, resolveScenes } from './previewModel';
+
+const people = [{ id: '1' }];
+
+describe('resolveGroupOutcome', () => {
+ it('answers in any group by default', () => {
+ expect(resolveGroupOutcome({})).toEqual({ kind: 'answer' });
+ expect(resolveGroupOutcome({ groupPolicy: 'open' })).toEqual({ kind: 'answer' });
+ });
+
+ it('tells the sender when group replies are off, instead of staying silent', () => {
+ expect(resolveGroupOutcome({ groupPolicy: 'disabled' })).toEqual({
+ kind: 'notice',
+ noticeKey: 'group.disabled',
+ });
+ });
+
+ it('answers with a scope note when only listed groups are enabled', () => {
+ expect(
+ resolveGroupOutcome({ groupAllowFrom: [{ id: '1' }], groupPolicy: 'allowlist' }),
+ ).toEqual({ kind: 'answer', scopeNote: 'groupAllowlist' });
+ });
+
+ it('fails closed with a notice on an empty group list', () => {
+ expect(resolveGroupOutcome({ groupAllowFrom: [], groupPolicy: 'allowlist' })).toEqual({
+ kind: 'notice',
+ noticeKey: 'group.allowlist',
+ });
+ expect(resolveGroupOutcome({ groupPolicy: 'allowlist' }).kind).toBe('notice');
+ });
+
+ it('lets the global people list turn a stranger away first, whatever the group policy', () => {
+ for (const groupPolicy of ['open', 'allowlist', 'disabled']) {
+ expect(resolveGroupOutcome({ allowFrom: people, groupPolicy })).toEqual({
+ kind: 'notice',
+ noticeKey: 'sender.rejected',
+ });
+ }
+ });
+
+ it('applies the people list in groups even under pairing', () => {
+ expect(resolveGroupOutcome({ allowFrom: people, dmPolicy: 'pairing' }).noticeKey).toBe(
+ 'sender.rejected',
+ );
+ });
+});
+
+describe('resolveDmOutcome', () => {
+ it('answers anyone when DMs are open and the list is empty', () => {
+ expect(resolveDmOutcome({ allowFrom: [], dmPolicy: 'open' })).toEqual({ kind: 'answer' });
+ expect(resolveDmOutcome({})).toEqual({ kind: 'answer' });
+ });
+
+ it.each([
+ ['allowlist', 'dm.allowlist'],
+ ['disabled', 'dm.disabled'],
+ ])('tells a stranger what %s means', (dmPolicy, noticeKey) => {
+ expect(resolveDmOutcome({ dmPolicy })).toEqual({ kind: 'notice', noticeKey });
+ });
+
+ it('offers a pairing code even when the list is already filled', () => {
+ expect(resolveDmOutcome({ allowFrom: people, dmPolicy: 'pairing' })).toEqual({
+ kind: 'notice',
+ noticeKey: 'dm.pairing',
+ });
+ });
+
+ it('turns a stranger away when an open policy sits behind a filled list', () => {
+ expect(resolveDmOutcome({ allowFrom: people, dmPolicy: 'open' })).toEqual({
+ kind: 'notice',
+ noticeKey: 'dm.allowlist',
+ });
+ expect(resolveDmOutcome({ allowFrom: people, dmPolicy: 'disabled' }).noticeKey).toBe(
+ 'dm.allowlist',
+ );
+ });
+});
+
+describe('resolveScenes', () => {
+ it('adds the DM scene only when the platform has a DM policy', () => {
+ expect(resolveScenes(['dmPolicy', 'groupPolicy'])).toEqual(['group', 'dm']);
+ expect(resolveScenes(['displayToolCalls'])).toEqual(['group']);
+ });
+});
+
+describe('pickKeywords', () => {
+ it('keeps the first three non-empty keywords, trimmed', () => {
+ expect(
+ pickKeywords([
+ { keyword: ' bug ' },
+ { keyword: '' },
+ { keyword: 'urgent' },
+ { keyword: 'a' },
+ { keyword: 'b' },
+ ]),
+ ).toEqual(['bug', 'urgent', 'a']);
+ });
+
+ it('ignores anything that is not a keyword list', () => {
+ expect(pickKeywords(undefined)).toEqual([]);
+ expect(pickKeywords('bug')).toEqual([]);
+ expect(pickKeywords([null, 3])).toEqual([]);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/previewModel.ts b/src/features/AgentChannel/PlatformDetail/previewModel.ts
new file mode 100644
index 00000000000..4382ab14c8d
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/previewModel.ts
@@ -0,0 +1,96 @@
+/**
+ * What the Quick view shows is decided here, away from the component: given the
+ * values currently in the form, what does the bot do for a message in a group,
+ * and for one in a DM? The rules follow the runtime's access gate
+ * (`shouldAllowSender`, `shouldHandleDm`, `shouldHandleGroup` and the router's
+ * `passGatesOrNotify`); the wording is the component's job.
+ */
+
+export type PreviewScene = 'dm' | 'group';
+
+export interface PreviewSettings {
+ allowFrom?: unknown;
+ dmPolicy?: string;
+ groupAllowFrom?: unknown;
+ groupPolicy?: string;
+ watchKeywords?: unknown;
+}
+
+export interface PreviewOutcome {
+ kind: 'answer' | 'notice';
+ /** The bot's own system reply, under `channel.quickView.` */
+ noticeKey?:
+ | 'dm.allowlist'
+ | 'dm.disabled'
+ | 'dm.pairing'
+ | 'group.allowlist'
+ | 'group.disabled'
+ | 'sender.rejected';
+ /** A one-line caveat shown under an answer. */
+ scopeNote?: 'groupAllowlist';
+}
+
+const hasEntries = (value: unknown) => Array.isArray(value) && value.length > 0;
+
+/**
+ * The preview's sender is someone who is neither on the list nor the bot's
+ * owner (the owner passes every gate), so the rules read as a stranger meets
+ * them. The order is the router's: the global list first, then the scope's
+ * own policy. Every refusal is a real reply posted in the chat, never silence.
+ */
+export const resolveGroupOutcome = (settings: PreviewSettings): PreviewOutcome => {
+ if (hasEntries(settings.allowFrom)) return { kind: 'notice', noticeKey: 'sender.rejected' };
+
+ switch (settings.groupPolicy) {
+ case 'disabled': {
+ return { kind: 'notice', noticeKey: 'group.disabled' };
+ }
+ case 'allowlist': {
+ // An empty list fails closed: the bot is enabled in no group.
+ return hasEntries(settings.groupAllowFrom)
+ ? { kind: 'answer', scopeNote: 'groupAllowlist' }
+ : { kind: 'notice', noticeKey: 'group.allowlist' };
+ }
+ default: {
+ return { kind: 'answer' };
+ }
+ }
+};
+
+export const resolveDmOutcome = (settings: PreviewSettings): PreviewOutcome => {
+ // Pairing is the one policy that skips the global list, so a stranger can
+ // reach a pairing code instead of being turned away first.
+ if (settings.dmPolicy === 'pairing') return { kind: 'notice', noticeKey: 'dm.pairing' };
+ if (hasEntries(settings.allowFrom)) return { kind: 'notice', noticeKey: 'dm.allowlist' };
+
+ switch (settings.dmPolicy) {
+ case 'allowlist': {
+ return { kind: 'notice', noticeKey: 'dm.allowlist' };
+ }
+ case 'disabled': {
+ return { kind: 'notice', noticeKey: 'dm.disabled' };
+ }
+ default: {
+ return { kind: 'answer' };
+ }
+ }
+};
+
+/** Group is always there; the DM scene only exists for platforms with a DM policy. */
+export const resolveScenes = (settingKeys: string[]): PreviewScene[] =>
+ settingKeys.includes('dmPolicy') ? ['group', 'dm'] : ['group'];
+
+/** Up to three watch keywords, trimmed and without empty rows. */
+export const pickKeywords = (watchKeywords: unknown, limit = 3): string[] => {
+ if (!Array.isArray(watchKeywords)) return [];
+
+ return watchKeywords
+ .map((entry) =>
+ entry && typeof entry === 'object'
+ ? String((entry as { keyword?: unknown }).keyword ?? '')
+ : '',
+ )
+ .map((keyword) => keyword.trim())
+ .filter(Boolean)
+ .slice(0, limit);
+};
diff --git a/src/features/AgentChannel/PlatformDetail/replySettings.test.ts b/src/features/AgentChannel/PlatformDetail/replySettings.test.ts
new file mode 100644
index 00000000000..e40977a8730
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/replySettings.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it } from 'vitest';
+
+import { hasPendingChanges, pickKeys, replyDiffers } from './replySettings';
+
+const KEYS = ['displayToolCalls', 'showUsageStats', 'watchKeywords'];
+
+describe('pickKeys', () => {
+ it('takes only the keys asked for that have a value', () => {
+ expect(
+ pickKeys({ charLimit: 1, displayToolCalls: true, showUsageStats: undefined }, KEYS),
+ ).toEqual({
+ displayToolCalls: true,
+ });
+ expect(pickKeys(undefined, KEYS)).toEqual({});
+ });
+});
+
+describe('replyDiffers', () => {
+ it('is false when the form matches what is stored', () => {
+ expect(
+ replyDiffers({ displayToolCalls: true, watchKeywords: [] }, { displayToolCalls: true }, KEYS),
+ ).toBe(false);
+ });
+
+ it('is true when a toggle differs', () => {
+ expect(replyDiffers({ displayToolCalls: true }, { displayToolCalls: false }, KEYS)).toBe(true);
+ });
+
+ it('ignores a row field the form leaves empty', () => {
+ const stored = { watchKeywords: [{ keyword: 'bug' }] };
+ expect(
+ replyDiffers({ watchKeywords: [{ instruction: '', keyword: 'bug' }] }, stored, KEYS),
+ ).toBe(false);
+ expect(
+ replyDiffers({ watchKeywords: [{ keyword: 'bug' }, { keyword: 'x' }] }, stored, KEYS),
+ ).toBe(true);
+ });
+
+ it('ignores keys that are not reply keys', () => {
+ expect(replyDiffers({ charLimit: 1 }, { charLimit: 2 }, KEYS)).toBe(false);
+ });
+});
+
+describe('hasPendingChanges', () => {
+ const stored = {
+ applicationId: '1',
+ credentials: { botToken: '••••' },
+ settings: { charLimit: 2000, displayToolCalls: false },
+ };
+
+ it('is false for an untouched form', () => {
+ expect(hasPendingChanges(stored, stored, KEYS)).toBe(false);
+ });
+
+ it('does not count changes to the keys that save themselves', () => {
+ const values = { ...stored, settings: { ...stored.settings, displayToolCalls: true } };
+ expect(hasPendingChanges(values, stored, KEYS)).toBe(false);
+ });
+
+ it('counts a change to anything else, including a credential', () => {
+ expect(
+ hasPendingChanges(
+ { ...stored, settings: { ...stored.settings, charLimit: 500 } },
+ stored,
+ KEYS,
+ ),
+ ).toBe(true);
+ expect(hasPendingChanges({ ...stored, credentials: { botToken: 'new' } }, stored, KEYS)).toBe(
+ true,
+ );
+ });
+
+ it('goes back to clean when a change is undone', () => {
+ const edited = { ...stored, settings: { ...stored.settings, charLimit: 500 } };
+ expect(hasPendingChanges(edited, stored, KEYS)).toBe(true);
+ expect(hasPendingChanges({ ...edited, settings: stored.settings }, stored, KEYS)).toBe(false);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/replySettings.ts b/src/features/AgentChannel/PlatformDetail/replySettings.ts
new file mode 100644
index 00000000000..90bcae8858b
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/replySettings.ts
@@ -0,0 +1,67 @@
+import isEqual from 'fast-deep-equal';
+
+import type { ChannelValues } from './channelTabs';
+
+/**
+ * Reply style is the one tab whose settings take effect as soon as they are
+ * changed, so the page has to tell "reply settings that differ from what is
+ * stored" (save them now) apart from "everything else that differs" (wait for
+ * the Save button).
+ */
+
+type Settings = Record<string, unknown> | undefined;
+
+/** A value as it would be stored: no `undefined`, no empty strings inside rows. */
+const canonical = (value: unknown): unknown => {
+ if (Array.isArray(value)) return value.map(canonical);
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value)
+ .filter(([, entry]) => entry !== undefined && entry !== '')
+ .map(([key, entry]) => [key, canonical(entry)]),
+ );
+ }
+ return value;
+};
+
+export const pickKeys = (settings: Settings, keys: string[]): Record<string, unknown> =>
+ Object.fromEntries(
+ keys.filter((key) => settings?.[key] !== undefined).map((key) => [key, settings![key]]),
+ );
+
+/** A list that was never stored and an empty list mean the same thing. */
+const comparable = (value: unknown): unknown => {
+ const next = canonical(value ?? null);
+ return Array.isArray(next) && next.length === 0 ? null : next;
+};
+
+/** Whether any of `keys` differs between the form and what is stored. */
+export const replyDiffers = (current: Settings, stored: Settings, keys: string[]): boolean =>
+ keys.some((key) => !isEqual(comparable(current?.[key]), comparable(stored?.[key])));
+
+const withoutKeys = (settings: Settings, keys: string[]): Settings =>
+ settings
+ ? Object.fromEntries(Object.entries(settings).filter(([key]) => !keys.includes(key)))
+ : settings;
+
+/**
+ * Whether the form holds changes that still need the Save button: everything
+ * that differs from the stored values, except the keys that save themselves.
+ */
+export const hasPendingChanges = (
+ values: ChannelValues,
+ stored: ChannelValues,
+ selfSavingKeys: string[],
+): boolean =>
+ !isEqual(
+ canonical({
+ applicationId: values.applicationId,
+ credentials: values.credentials,
+ settings: withoutKeys(values.settings, selfSavingKeys),
+ }),
+ canonical({
+ applicationId: stored.applicationId,
+ credentials: stored.credentials,
+ settings: withoutKeys(stored.settings, selfSavingKeys),
+ }),
+ );
diff --git a/src/features/AgentChannel/PlatformDetail/saveCoordinator.test.ts b/src/features/AgentChannel/PlatformDetail/saveCoordinator.test.ts
new file mode 100644
index 00000000000..21ce134d562
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/saveCoordinator.test.ts
@@ -0,0 +1,85 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createSaveCoordinator } from './saveCoordinator';
+
+const deferred = () => {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+};
+
+describe('createSaveCoordinator', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('drops a pending autosave when Save is pressed before its delay runs out', async () => {
+ const coordinator = createSaveCoordinator();
+ const autosave = vi.fn(async () => undefined);
+
+ coordinator.scheduleAuto(autosave, 400);
+ await coordinator.beginExplicit();
+ await vi.advanceTimersByTimeAsync(1000);
+ coordinator.endExplicit();
+
+ expect(autosave).not.toHaveBeenCalled();
+ });
+
+ it('lets an autosave already on its way finish before Save writes', async () => {
+ const coordinator = createSaveCoordinator();
+ const write = deferred();
+ const order: string[] = [];
+
+ void coordinator.runAuto(async () => {
+ await write.promise;
+ order.push('autosave');
+ });
+ const save = coordinator.beginExplicit().then(() => order.push('save'));
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(order).toEqual([]);
+ write.resolve();
+ await save;
+
+ expect(order).toEqual(['autosave', 'save']);
+ });
+
+ it('keeps autosaves out while Save is running, and lets them back in afterwards', async () => {
+ const coordinator = createSaveCoordinator();
+ const autosave = vi.fn(async () => undefined);
+
+ await coordinator.beginExplicit();
+ expect(coordinator.isExplicit()).toBe(true);
+ await coordinator.runAuto(autosave);
+ expect(autosave).not.toHaveBeenCalled();
+
+ coordinator.endExplicit();
+ await coordinator.runAuto(autosave);
+ expect(autosave).toHaveBeenCalledOnce();
+ });
+
+ it('never runs two autosaves at once', async () => {
+ const coordinator = createSaveCoordinator();
+ const write = deferred();
+ const second = vi.fn(async () => undefined);
+
+ const first = coordinator.runAuto(() => write.promise);
+ await coordinator.runAuto(second);
+ write.resolve();
+ await first;
+
+ expect(second).not.toHaveBeenCalled();
+ });
+
+ it('still lets Save through when the running autosave fails', async () => {
+ const coordinator = createSaveCoordinator();
+
+ void coordinator.runAuto(() => Promise.reject(new Error('offline'))).catch(() => undefined);
+ await expect(coordinator.beginExplicit()).resolves.toBeUndefined();
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts b/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts
new file mode 100644
index 00000000000..2902e2626c0
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/saveCoordinator.ts
@@ -0,0 +1,46 @@
+/**
+ * Keeps the page's two writers apart. Reply settings save themselves a moment after they change;
+ * the Save button writes everything. Both replace the whole settings column, so if an autosave
+ * built from the previously stored values landed after an explicit save, it would silently undo
+ * what that save had just confirmed.
+ *
+ * - An explicit save cancels a pending autosave and waits for one already on its way.
+ * - No autosave starts while an explicit save is running.
+ * - Autosaves never overlap each other.
+ */
+export const createSaveCoordinator = () => {
+ let explicit = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let autoRun: Promise<void> | undefined;
+
+ const runAuto = async (save: () => Promise<void>) => {
+ if (explicit || autoRun) return;
+ autoRun = save().finally(() => {
+ autoRun = undefined;
+ });
+ await autoRun;
+ };
+
+ return {
+ /** Start an explicit save: drop the pending autosave and let a running one finish first. */
+ beginExplicit: async () => {
+ clearTimeout(timer);
+ explicit = true;
+ await autoRun?.catch(() => undefined);
+ },
+ dispose: () => clearTimeout(timer),
+ endExplicit: () => {
+ explicit = false;
+ },
+ /** An explicit save is running; an autosave that got this far should stand down. */
+ isExplicit: () => explicit,
+ runAuto,
+ /** (Re)start the delay before an autosave. */
+ scheduleAuto: (save: () => Promise<void>, delay: number) => {
+ clearTimeout(timer);
+ timer = setTimeout(() => void runAuto(save), delay);
+ },
+ };
+};
+
+export type SaveCoordinator = ReturnType<typeof createSaveCoordinator>;
diff --git a/src/features/AgentChannel/PlatformDetail/sections.test.ts b/src/features/AgentChannel/PlatformDetail/sections.test.ts
deleted file mode 100644
index 3216c450738..00000000000
--- a/src/features/AgentChannel/PlatformDetail/sections.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import { schema as discordSchema } from '@/server/services/bot/platforms/discord/schema';
-import { sharedSchema as feishuSchema } from '@/server/services/bot/platforms/feishu/definitions/schema';
-import { schema as imessageSchema } from '@/server/services/bot/platforms/imessage/schema';
-import { schema as lineSchema } from '@/server/services/bot/platforms/line/schema';
-import { schema as qqSchema } from '@/server/services/bot/platforms/qq/schema';
-import { schema as slackSchema } from '@/server/services/bot/platforms/slack/schema';
-import { schema as telegramSchema } from '@/server/services/bot/platforms/telegram/schema';
-import type { FieldSchema } from '@/server/services/bot/platforms/types';
-import { schema as wechatSchema } from '@/server/services/bot/platforms/wechat/schema';
-
-import { getSettingsSection, groupSettingsFields } from './sections';
-
-const settingsOf = (schema: FieldSchema[]) =>
- schema.find((section) => section.key === 'settings')?.properties ?? [];
-
-const PLATFORM_SCHEMAS: Record<string, FieldSchema[]> = {
- discord: discordSchema,
- feishu: feishuSchema,
- imessage: imessageSchema,
- line: lineSchema,
- qq: qqSchema,
- slack: slackSchema,
- telegram: telegramSchema,
- wechat: wechatSchema,
-};
-
-describe('channel settings sections', () => {
- it.each(Object.entries(PLATFORM_SCHEMAS))(
- 'files every %s setting under a named section, never the fallback',
- (_platform, schema) => {
- const unmapped = settingsOf(schema)
- .map((field) => field.key)
- .filter((key) => getSettingsSection(key) === 'other');
-
- expect(unmapped).toEqual([]);
- },
- );
-
- it('puts who-can-talk policies together, ahead of reply behaviour', () => {
- const { sections } = groupSettingsFields(settingsOf(discordSchema));
-
- expect(sections.map((section) => section.key)).toEqual([
- 'access',
- 'account',
- 'replies',
- 'wake',
- ]);
- expect(sections[0].fields.map((field) => field.key)).toEqual([
- 'dmPolicy',
- 'groupPolicy',
- 'groupAllowFrom',
- 'allowFrom',
- ]);
- });
-
- it('moves the connection mode next to the credentials', () => {
- const { connection, sections } = groupSettingsFields(settingsOf(slackSchema));
-
- expect(connection.map((field) => field.key)).toEqual(['connectionMode']);
- expect(sections.flatMap((section) => section.fields).map((field) => field.key)).not.toContain(
- 'connectionMode',
- );
- });
-
- it('keeps an unknown key visible under the fallback section', () => {
- const { sections } = groupSettingsFields([
- { key: 'charLimit', label: '', type: 'number' },
- { key: 'somethingNew', label: '', type: 'string' },
- ]);
-
- expect(sections).toEqual([
- { fields: [{ key: 'charLimit', label: '', type: 'number' }], key: 'replies' },
- { fields: [{ key: 'somethingNew', label: '', type: 'string' }], key: 'other' },
- ]);
- });
-
- it('drops sections a platform has no fields for', () => {
- const { sections } = groupSettingsFields(settingsOf(wechatSchema));
-
- expect(sections.map((section) => section.key)).toEqual(['replies', 'wake']);
- });
-});
diff --git a/src/features/AgentChannel/PlatformDetail/sections.ts b/src/features/AgentChannel/PlatformDetail/sections.ts
deleted file mode 100644
index 68ba41a05e5..00000000000
--- a/src/features/AgentChannel/PlatformDetail/sections.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import type { FieldSchema } from '@/server/services/bot/platforms/types';
-
-/**
- * Sections of a channel's settings, in page order. Each answers one question an
- * operator has after the bot is connected: who may talk to it, which platform
- * account is theirs, how it replies, and when it wakes up on its own.
- */
-export const SETTINGS_SECTIONS = ['access', 'account', 'replies', 'wake', 'other'] as const;
-
-export type SettingsSectionKey = (typeof SETTINGS_SECTIONS)[number];
-
-/**
- * Where a settings key renders. `connection` keys join the credential card,
- * because they change how the bot reaches the platform rather than how it
- * behaves. Kept on the client so the platform schemas stay presentation-free;
- * a key nobody mapped falls through to `other` instead of disappearing.
- */
-const SECTION_BY_KEY: Record<string, SettingsSectionKey | 'connection'> = {
- allowFrom: 'access',
- charLimit: 'replies',
- concurrency: 'replies',
- connectionMode: 'connection',
- debounceMs: 'replies',
- displayToolCalls: 'replies',
- dmPolicy: 'access',
- groupAllowFrom: 'access',
- groupPolicy: 'access',
- guestPolicy: 'access',
- historyLimit: 'replies',
- reactionMode: 'replies',
- serverId: 'account',
- showUsageStats: 'replies',
- userId: 'account',
- watchKeywords: 'wake',
-};
-
-export const getSettingsSection = (key: string): SettingsSectionKey | 'connection' =>
- SECTION_BY_KEY[key] ?? (key.startsWith('botWake') ? 'wake' : 'other');
-
-export interface SettingsSectionGroup {
- fields: FieldSchema[];
- key: SettingsSectionKey;
-}
-
-/**
- * Splits flattened settings fields into the connection fields and the ordered,
- * non-empty settings sections. Fields keep their schema order inside a section.
- */
-export const groupSettingsFields = (fields: FieldSchema[]) => {
- const connection: FieldSchema[] = [];
- const buckets = new Map<SettingsSectionKey, FieldSchema[]>();
-
- for (const field of fields) {
- const section = getSettingsSection(field.key);
- if (section === 'connection') {
- connection.push(field);
- continue;
- }
- const bucket = buckets.get(section) ?? [];
- bucket.push(field);
- buckets.set(section, bucket);
- }
-
- const sections: SettingsSectionGroup[] = SETTINGS_SECTIONS.flatMap((key) => {
- const sectionFields = buckets.get(key);
- return sectionFields?.length ? [{ fields: sectionFields, key }] : [];
- });
-
- return { connection, sections };
-};
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
new file mode 100644
index 00000000000..192f084079a
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FieldSchema } from '@/server/services/bot/platforms/types';
+
+import { getSchemaFields, groupSettingsFields } from './settingsGroups';
+
+const field = (key: string): FieldSchema => ({ key, label: key, type: 'string' });
+
+describe('groupSettingsFields', () => {
+ it('sorts fields into connect, access, reply and advanced, ordered by how a person decides them', () => {
+ const groups = groupSettingsFields(
+ [
+ 'serverId',
+ 'charLimit',
+ 'groupPolicy',
+ 'watchKeywords',
+ 'allowFrom',
+ 'dmPolicy',
+ 'userId',
+ 'displayToolCalls',
+ 'reactionMode',
+ 'historyLimit',
+ ].map(field),
+ );
+
+ expect(groups.map((g) => [g.key, g.fields.map((f) => f.key)])).toEqual([
+ ['access', ['userId', 'serverId', 'dmPolicy', 'allowFrom', 'groupPolicy']],
+ ['wake', ['watchKeywords']],
+ ['reply', ['displayToolCalls', 'reactionMode']],
+ ['advanced', ['charLimit', 'historyLimit']],
+ ]);
+ });
+
+ it('keeps a field it does not know in advanced, in schema order, so nothing disappears', () => {
+ const groups = groupSettingsFields(['mysterySetting', 'dmPolicy', 'someNewSetting'].map(field));
+
+ expect(groups.find((g) => g.key === 'advanced')?.fields.map((f) => f.key)).toEqual([
+ 'mysterySetting',
+ 'someNewSetting',
+ ]);
+ });
+
+ it('puts how the bot reaches the platform with the connection, and your server with your own ID', () => {
+ const groups = groupSettingsFields(
+ ['charLimit', 'connectionMode', 'serverId', 'userId'].map(field),
+ );
+
+ expect(groups.find((g) => g.key === 'connect')?.fields.map((f) => f.key)).toEqual([
+ 'connectionMode',
+ ]);
+ expect(groups.find((g) => g.key === 'access')?.fields.map((f) => f.key)).toEqual([
+ 'userId',
+ 'serverId',
+ ]);
+ expect(groups.find((g) => g.key === 'advanced')?.fields.map((f) => f.key)).toEqual([
+ 'charLimit',
+ ]);
+ });
+
+ it('puts the watch keywords and the bot-wake options in one group between access and replies', () => {
+ const groups = groupSettingsFields(
+ [
+ 'charLimit',
+ 'botWakeEnabled',
+ 'displayToolCalls',
+ 'botWakeMode',
+ 'dmPolicy',
+ 'watchKeywords',
+ ].map(field),
+ );
+
+ expect(groups.map((g) => [g.key, g.fields.map((f) => f.key)])).toEqual([
+ ['access', ['dmPolicy']],
+ ['wake', ['watchKeywords', 'botWakeEnabled', 'botWakeMode']],
+ ['reply', ['displayToolCalls']],
+ ['advanced', ['charLimit']],
+ ]);
+ });
+
+ it('drops sections a platform has no fields for', () => {
+ const groups = groupSettingsFields(['displayToolCalls', 'reactionMode'].map(field));
+
+ expect(groups.map((g) => g.key)).toEqual(['reply']);
+ });
+
+ it('returns nothing for a platform without settings', () => {
+ expect(groupSettingsFields([])).toEqual([]);
+ });
+});
+
+describe('getSchemaFields', () => {
+ const schema: FieldSchema[] = [
+ {
+ key: 'settings',
+ label: 'settings',
+ properties: [
+ field('charLimit'),
+ { ...field('botWakeEnabled'), featureFlag: 'enableBotWake' },
+ ],
+ type: 'object',
+ },
+ ];
+
+ it('hides a field behind a rollout flag until the flag is on', () => {
+ expect(getSchemaFields(schema, 'settings').map((f) => f.key)).toEqual(['charLimit']);
+ expect(getSchemaFields(schema, 'settings', { enableBotWake: false }).map((f) => f.key)).toEqual(
+ ['charLimit'],
+ );
+ expect(getSchemaFields(schema, 'settings', { enableBotWake: true }).map((f) => f.key)).toEqual([
+ 'charLimit',
+ 'botWakeEnabled',
+ ]);
+ });
+});
diff --git a/src/features/AgentChannel/PlatformDetail/settingsGroups.ts b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
new file mode 100644
index 00000000000..db46da5eae1
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/settingsGroups.ts
@@ -0,0 +1,95 @@
+import type { FieldSchema } from '@/server/services/bot/platforms/types';
+
+import { isFieldReleased } from './formState';
+
+/**
+ * The fields under one top-level section of a platform schema, with nested
+ * object sections flattened into their children. Dev-only fields stay out of
+ * production builds, and a field behind a rollout flag shows only when the
+ * user's flag is on.
+ */
+export const getSchemaFields = (
+ schema: FieldSchema[],
+ sectionKey: string,
+ featureFlags?: Record<string, unknown>,
+): FieldSchema[] => {
+ const section = schema.find((field) => field.key === sectionKey);
+ if (!section?.properties) return [];
+
+ const shown = (field: FieldSchema) =>
+ (!field.devOnly || __DEV__) && isFieldReleased(field, featureFlags);
+
+ return section.properties.filter(shown).flatMap((field) => {
+ if (field.type === 'object' && field.properties) return field.properties.filter(shown);
+ return field;
+ });
+};
+
+export type SettingsGroupKey = 'access' | 'advanced' | 'connect' | 'reply' | 'wake';
+
+export interface SettingsGroup {
+ fields: FieldSchema[];
+ key: SettingsGroupKey;
+}
+
+/**
+ * Who the bot talks to, in the order a person decides it: who you are and which
+ * server is yours, then DMs
+ * (and the list they lean on), then groups.
+ */
+const ACCESS_KEYS = [
+ 'userId',
+ 'serverId',
+ 'dmPolicy',
+ 'allowFrom',
+ 'guestPolicy',
+ 'groupPolicy',
+ 'groupAllowFrom',
+];
+
+/** What a reply looks like in the chat. */
+export const REPLY_KEYS = ['displayToolCalls', 'showUsageStats', 'reactionMode'];
+
+/**
+ * When the bot speaks up without being @mentioned: first the keywords that wake it, then the
+ * bot-wake rules, which all share one prefix and judge the messages nobody addressed to it.
+ */
+const WAKE_KEYS = ['watchKeywords'];
+export const WAKE_KEY_PREFIX = 'botWake';
+
+/** How the bot reaches the platform: how events arrive. */
+const CONNECT_KEYS = ['connectionMode'];
+
+/**
+ * Split a platform's flat settings fields into the sections the page shows (one per tab).
+ *
+ * The schema stays the single source of truth: a field a platform adds later
+ * that is not named above lands in `advanced`, so nothing a schema declares can
+ * vanish from the page. Empty sections are dropped, so a platform that has no
+ * access controls (WeChat, LINE) simply has no such section.
+ */
+export const groupSettingsFields = (fields: FieldSchema[]): SettingsGroup[] => {
+ const byKey = new Map(fields.map((field) => [field.key, field]));
+ const pick = (keys: string[]) =>
+ keys.map((key) => byKey.get(key)).filter((field): field is FieldSchema => !!field);
+
+ const connect = pick(CONNECT_KEYS);
+ const access = pick(ACCESS_KEYS);
+ const reply = pick(REPLY_KEYS);
+ const wake = [
+ ...pick(WAKE_KEYS),
+ ...fields.filter((field) => field.key.startsWith(WAKE_KEY_PREFIX)),
+ ];
+ const placed = new Set([...connect, ...access, ...wake, ...reply].map((field) => field.key));
+ const advanced = fields.filter((field) => !placed.has(field.key));
+
+ return (
+ [
+ { fields: connect, key: 'connect' },
+ { fields: access, key: 'access' },
+ { fields: wake, key: 'wake' },
+ { fields: reply, key: 'reply' },
+ { fields: advanced, key: 'advanced' },
+ ] satisfies SettingsGroup[]
+ ).filter((group) => group.fields.length > 0);
+};
diff --git a/src/features/AgentChannel/PlatformDetail/useNarrowLayout.ts b/src/features/AgentChannel/PlatformDetail/useNarrowLayout.ts
new file mode 100644
index 00000000000..d486eaf3a9c
--- /dev/null
+++ b/src/features/AgentChannel/PlatformDetail/useNarrowLayout.ts
@@ -0,0 +1,22 @@
+import { useEffect, useState } from 'react';
+
+/** Below this width the page has no room for the chat preview beside the form. */
+const NARROW_QUERY = '(max-width: 1100px)';
+
+/** Whether the window is too narrow for the split layout. */
+export const useNarrowLayout = () => {
+ const [narrow, setNarrow] = useState(
+ () => typeof window !== 'undefined' && !!window.matchMedia?.(NARROW_QUERY).matches,
+ );
+
+ useEffect(() => {
+ const query = window.matchMedia?.(NARROW_QUERY);
+ if (!query) return;
+ const update = () => setNarrow(query.matches);
+ update();
+ query.addEventListener('change', update);
+ return () => query.removeEventListener('change', update);
+ }, []);
+
+ return narrow;
+};
diff --git a/src/features/AgentChannel/platform/imessage/CredentialExtras.tsx b/src/features/AgentChannel/platform/imessage/CredentialExtras.tsx
index 7bbe45c35ec..ec9a068285b 100644
--- a/src/features/AgentChannel/platform/imessage/CredentialExtras.tsx
+++ b/src/features/AgentChannel/platform/imessage/CredentialExtras.tsx
@@ -2,9 +2,9 @@
import { isDesktop } from '@lobechat/const';
import type { ImessageBridgeConfig, ImessageBridgeStatus } from '@lobechat/electron-client-ipc';
-import { Button, createStaticStyles, Flexbox, Icon, Switch, Tag, Text, toast } from '@lobehub/ui';
+import { Button, createStaticStyles, Flexbox, Switch, Tag, Text, toast } from '@lobehub/ui';
import { Form, useFormInstance, useWatch } from '@lobehub/ui/form';
-import { KeyRound, Link2, Wrench } from 'lucide-react';
+import { Wrench } from 'lucide-react';
import { memo, use, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -26,10 +26,6 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
background: ${cssVar.colorBgContainer};
`,
- fieldIcon: css`
- flex: none;
- color: ${cssVar.colorTextSecondary};
- `,
headerIcon: css`
overflow: hidden;
flex: none;
@@ -252,9 +248,7 @@ const CredentialExtras = memo(() => {
{/* Middle: the credential fields the operator fills in. */}
<Form.Field
- avatar={<Icon className={styles.fieldIcon} icon={Link2} size={20} />}
- minWidth={'max(50%, 360px)'}
- variant="outlined"
+ layout="vertical"
label={
<Flexbox horizontal align="center" gap={8}>
{t('channel.imessage.blueBubblesServerUrl')}
@@ -277,9 +271,7 @@ const CredentialExtras = memo(() => {
</Form.Field>
<Form.Field
divider
- avatar={<Icon className={styles.fieldIcon} icon={KeyRound} size={20} />}
- minWidth={'max(50%, 360px)'}
- variant="outlined"
+ layout="vertical"
label={
<Flexbox horizontal align="center" gap={8}>
{t('channel.imessage.blueBubblesPassword')}
diff --git a/src/features/AgentChannel/platform/line/CredentialExtras.tsx b/src/features/AgentChannel/platform/line/CredentialExtras.tsx
index be9f369eb54..3c69058366f 100644
--- a/src/features/AgentChannel/platform/line/CredentialExtras.tsx
+++ b/src/features/AgentChannel/platform/line/CredentialExtras.tsx
@@ -56,7 +56,7 @@ const CredentialExtras = memo<PlatformCredentialExtrasProps>(({ disabled }) => {
icon={<Download size={14} />}
loading={loading}
size="small"
- style={{ alignSelf: 'flex-start', marginBlockStart: 4 }}
+ style={{ alignSelf: 'flex-start', marginBlockEnd: 12 }}
type="default"
disabled={
disabled || !channelAccessToken?.trim() || isMaskedBotCredential(channelAccessToken)
diff --git a/src/features/AgentChannel/platform/wechat/ConnectedInfo.tsx b/src/features/AgentChannel/platform/wechat/ConnectedInfo.tsx
index f2b3a075f39..3022de69e41 100644
--- a/src/features/AgentChannel/platform/wechat/ConnectedInfo.tsx
+++ b/src/features/AgentChannel/platform/wechat/ConnectedInfo.tsx
@@ -1,9 +1,7 @@
'use client';
-import { createStaticStyles, Flexbox, Icon } from '@lobehub/ui';
+import { createStaticStyles, Flexbox } from '@lobehub/ui';
import { Form } from '@lobehub/ui/form';
-import type { LucideIcon } from 'lucide-react';
-import { Fingerprint, KeyRound, UserRound } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -11,11 +9,7 @@ import { FormInput, FormPassword } from '@/components/FormInput';
import QrCodeAuth from './QrCodeAuth';
-const styles = createStaticStyles(({ css, cssVar }) => ({
- fieldIcon: css`
- flex: none;
- color: ${cssVar.colorTextSecondary};
- `,
+const styles = createStaticStyles(({ css }) => ({
header: css`
display: flex;
align-items: center;
@@ -25,21 +19,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const ReadOnlyField = memo<{
divider?: boolean;
- icon: LucideIcon;
label: string;
password?: boolean;
value?: string;
-}>(({ divider, icon, label, password, value }) => {
+}>(({ divider, label, password, value }) => {
const InputComponent = password ? FormPassword : FormInput;
return (
- <Form.Field
- avatar={<Icon className={styles.fieldIcon} icon={icon} size={20} />}
- divider={divider}
- label={label}
- minWidth={'max(50%, 400px)'}
- variant="outlined"
- >
+ <Form.Field divider={divider} label={label} layout="vertical">
<InputComponent readOnly value={value || ''} />
</Form.Field>
);
@@ -82,30 +69,23 @@ const WechatConnectedInfo = memo<WechatConnectedInfoProps>(
/>
)}
{shouldShowApplicationId && (
- <ReadOnlyField
- icon={Fingerprint}
- label={t('channel.applicationId')}
- value={currentConfig.applicationId}
- />
+ <ReadOnlyField label={t('channel.applicationId')} value={currentConfig.applicationId} />
)}
{__DEV__ && (
<>
<ReadOnlyField
divider={shouldShowApplicationId}
- icon={Fingerprint}
label={t('channel.wechatBotId')}
value={currentConfig.credentials.botId}
/>
<ReadOnlyField
divider
password
- icon={KeyRound}
label={t('channel.botToken')}
value={currentConfig.credentials.botToken}
/>
<ReadOnlyField
divider
- icon={UserRound}
label={t('channel.wechatUserId')}
value={currentConfig.credentials.userId}
/>
diff --git a/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx b/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx
index eacd9c3e737..679981e8d8c 100644
--- a/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx
+++ b/src/features/AgentChannel/quickSetup/QuickSetupSection.tsx
@@ -1,8 +1,9 @@
'use client';
-import { cssVar, Flexbox, Text } from '@lobehub/ui';
+import { Button, Flexbox, Icon } from '@lobehub/ui';
import { Form, type FormInstance, useWatch } from '@lobehub/ui/form';
-import { memo, useMemo } from 'react';
+import { ChevronDown, ChevronRight } from 'lucide-react';
+import { memo, type ReactNode, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import FeishuQuickCreate, { type FeishuCreatedApp } from './FeishuQuickCreate';
@@ -22,30 +23,49 @@ interface QuickSetupSectionProps {
applicationId: string;
credentials: Record<string, string>;
}) => Promise<boolean> | void;
+ /** Saves and connects the bot from inside the steps; only offered while setting one up. */
+ onSave?: () => void;
platformId: string;
- /** Display name of the platform, used in the steps' summary line. */
- platformName: string;
+ /** Input for a credential field, shown under the step that asks for it. */
+ renderField?: (key: string) => ReactNode;
+ /** A save is running. */
+ saving?: boolean;
/** Who the created app is for (the agent id); a new scope starts a new scan. */
scope?: string;
}
/**
- * Cards above a channel's connection settings: Feishu / Lark create the bot app
- * from one scan (saved and connected through `onAuthenticated`), and every
- * platform gets its setup steps with links straight to the right console page.
- * The steps start open only while there is nothing saved and no scan to use.
+ * Top of a channel's page: Feishu / Lark create the bot app from one scan
+ * (saved and connected through `onAuthenticated`), and every platform gets its
+ * setup steps with links straight to the right console page. A saved bot has
+ * nothing left to set up, so the section folds away for it.
*/
const QuickSetupSection = memo<QuickSetupSectionProps>(
- ({ appName, disabled, form, hasConfig, onAuthenticated, platformId, platformName, scope }) => {
+ ({
+ appName,
+ disabled,
+ form,
+ hasConfig,
+ onAuthenticated,
+ onSave,
+ platformId,
+ renderField,
+ saving,
+ scope,
+ }) => {
const { t } = useTranslation('agent');
const applicationId = useWatch(form, (values) => values?.applicationId as string | undefined);
const guide = useMemo(
() => getSetupGuide(platformId, { applicationId, appName }),
[platformId, applicationId, appName],
);
+ // Platforms with a scan flow keep the manual steps one click away; the rest
+ // have no other way in, so the steps are open from the start.
+ const [stepsOpen, setStepsOpen] = useState(false);
if (!guide) return null;
const canScan = guide.scanToCreate && !hasConfig && !disabled && !!onAuthenticated;
+ const showSteps = !canScan || stepsOpen;
// Throws when the app can't be saved here, so the scan keeps its credentials.
const handleCreated = async ({ appId, appSecret, brand }: FeishuCreatedApp) => {
@@ -56,37 +76,62 @@ const QuickSetupSection = memo<QuickSetupSectionProps>(
};
return (
- <>
+ <Form.Group
+ // A saved bot has nothing left to set up, so the section folds away; a
+ // new one keeps it open and has no header to collapse.
+ collapsible={!!hasConfig}
+ defaultActive={!hasConfig}
+ keyValue={`setup-guide-${platformId}`}
+ title={t('channel.group.setup')}
+ variant={'filled'}
+ >
{canScan && (
- <Form.Group collapsible={false} variant={'filled'}>
- <Flexbox gap={12} style={{ paddingBlock: 16 }}>
- {/* Keyed so another agent or platform never inherits this scan. */}
- <FeishuQuickCreate
- appPreset={{ name: toRegistrationName(appName) }}
- key={`${scope ?? ''}:${platformId}`}
- platform={platformId as 'feishu' | 'lark'}
- scope={scope}
- onCreated={handleCreated}
- />
- <Text fontSize={12} style={{ color: cssVar.colorTextTertiary }}>
- {t('channel.quickSetup.manualToggle')}
- </Text>
- </Flexbox>
- </Form.Group>
+ <Flexbox gap={4} style={{ paddingBlock: 16 }}>
+ {/* Keyed so another agent or platform never inherits this scan. */}
+ <FeishuQuickCreate
+ appPreset={{ name: toRegistrationName(appName) }}
+ key={`${scope ?? ''}:${platformId}`}
+ platform={platformId as 'feishu' | 'lark'}
+ scope={scope}
+ onCreated={handleCreated}
+ />
+ <Button
+ icon={<Icon icon={stepsOpen ? ChevronDown : ChevronRight} />}
+ size={'small'}
+ style={{ alignSelf: 'flex-start', marginBlockStart: 8 }}
+ type={'text'}
+ onClick={() => setStepsOpen((open) => !open)}
+ >
+ {t('channel.quickSetup.manualToggle')}
+ </Button>
+ </Flexbox>
)}
- <Form.Group
- collapsible
- defaultActive={!hasConfig && !guide.scanToCreate}
- desc={t('channel.quickSetup.guideDesc', { name: platformName })}
- keyValue={`setup-guide-${platformId}`}
- title={t('channel.quickSetup.guideTitle')}
- variant={'filled'}
- >
- <div style={{ paddingBlock: 16 }}>
- <SetupGuide guide={guide} />
- </div>
- </Form.Group>
- </>
+ {showSteps && (
+ <SetupGuide
+ guide={guide}
+ renderField={renderField}
+ connectStep={
+ onSave && !hasConfig
+ ? {
+ action: (
+ <Button
+ disabled={disabled}
+ loading={saving}
+ style={{ flexShrink: 0 }}
+ type={'primary'}
+ onClick={onSave}
+ >
+ {t('channel.saveAndConnect')}
+ </Button>
+ ),
+ desc: t('channel.quickSetup.connect.desc'),
+ title: t('channel.quickSetup.connect.title'),
+ }
+ : undefined
+ }
+ />
+ )}
+ </Form.Group>
);
},
);
diff --git a/src/features/AgentChannel/quickSetup/SetupGuide.tsx b/src/features/AgentChannel/quickSetup/SetupGuide.tsx
index c21af4db0be..72234db013f 100644
--- a/src/features/AgentChannel/quickSetup/SetupGuide.tsx
+++ b/src/features/AgentChannel/quickSetup/SetupGuide.tsx
@@ -1,73 +1,140 @@
'use client';
-import { Button, createStaticStyles, cssVar, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
import { ExternalLinkIcon } from 'lucide-react';
-import { memo } from 'react';
+import { Fragment, memo, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
-import type { SetupGuide as SetupGuideModel } from './guides';
+import { connectStepIndex, type SetupGuide as SetupGuideModel } from './guides';
-const styles = createStaticStyles(({ css }) => ({
- index: css`
- display: flex;
- flex: none;
- align-items: center;
- justify-content: center;
-
- width: 22px;
- height: 22px;
- border-radius: 50%;
+const styles = stylex.create({
+ index: {
+ color: cssVar.colorTextTertiary,
+ flexShrink: 0,
+ fontVariantNumeric: 'tabular-nums',
+ minWidth: 16,
+ },
+ head: {
+ alignItems: 'flex-start',
+ columnGap: 12,
+ display: 'flex',
+ justifyContent: 'space-between',
+ },
+ row: {
+ display: 'flex',
+ flexDirection: 'column',
+ paddingBlock: 14,
+ rowGap: 12,
+ },
+ // Lines up with the step's text, past its number.
+ fields: {
+ paddingInlineStart: 28,
+ },
+ rowSeparated: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: 1,
+ },
+});
- font-size: 12px;
- font-weight: 600;
- color: ${cssVar.colorTextSecondary};
+interface ConnectStep {
+ /** The button that saves the form and brings the bot online. */
+ action: ReactNode;
+ desc: string;
+ title: string;
+}
- background: ${cssVar.colorFillSecondary};
- `,
-}));
+interface SetupGuideProps {
+ /**
+ * A step of its own for saving: a person setting up a bot reads the steps, not the page's
+ * bottom bar, so the save is asked for where the credentials end.
+ */
+ connectStep?: ConnectStep;
+ guide: SetupGuideModel;
+ /** The input for one credential field, shown under the step that asks for it. */
+ renderField?: (key: string) => ReactNode;
+}
/**
- * A platform's setup as numbered steps, each with a button straight to the
- * console page it happens on. Steps that need the app ID say so until the
- * form has it.
+ * A platform's setup as a plain list of steps: what to do, one line of how,
+ * and the link to the console page it happens on at the end of the row. A step
+ * that produces a credential has its input right under it, so each step is done
+ * where it is read. Steps that need the app ID say so until the form has it.
*/
-const SetupGuide = memo<{ guide: SetupGuideModel }>(({ guide }) => {
+const SetupGuide = memo<SetupGuideProps>(({ connectStep, guide, renderField }) => {
const { t } = useTranslation('agent');
const prefix = `channel.quickSetup.${guide.guide}`;
+ interface Item {
+ action?: ReactNode;
+ desc: string;
+ fields?: string[];
+ key: string;
+ title: string;
+ warning?: string;
+ }
+
+ const items: Item[] = guide.steps.map((step) => ({
+ action: step.link && (
+ <a href={step.link.href} rel={'noreferrer'} style={{ flexShrink: 0 }} target={'_blank'}>
+ <Button icon={<Icon icon={ExternalLinkIcon} />} size={'small'}>
+ {t(`channel.quickSetup.link.${step.link.label}`)}
+ </Button>
+ </a>
+ ),
+ desc: t(`${prefix}.${step.key}.desc` as any),
+ fields: step.fields,
+ key: step.key,
+ title: t(`${prefix}.${step.key}.title` as any),
+ warning: step.needsApplicationId ? t('channel.quickSetup.needsApplicationId') : undefined,
+ }));
+ if (connectStep)
+ items.splice(connectStepIndex(guide.steps), 0, {
+ action: connectStep.action,
+ desc: connectStep.desc,
+ key: 'connect',
+ title: connectStep.title,
+ });
+
return (
- <Flexbox data-testid={'channel-setup-guide'} gap={14}>
- {guide.steps.map((step, index) => (
- <Flexbox horizontal align={'flex-start'} gap={10} key={step.key}>
- <span className={styles.index}>{index + 1}</span>
- <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>
- <Text fontSize={13} weight={600}>
- {t(`${prefix}.${step.key}.title` as any)}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t(`${prefix}.${step.key}.desc` as any)}
- </Text>
- {step.link && (
- <a
- href={step.link.href}
- rel={'noreferrer'}
- style={{ alignSelf: 'flex-start' }}
- target={'_blank'}
- >
- <Button icon={<Icon icon={ExternalLinkIcon} />} size={'small'}>
- {t(`channel.quickSetup.link.${step.link.label}`)}
- </Button>
- </a>
- )}
- {step.needsApplicationId && (
- <Text fontSize={12} type={'secondary'}>
- {t('channel.quickSetup.needsApplicationId')}
+ <div data-testid={'channel-setup-guide'}>
+ {items.map((item, index) => (
+ <div
+ {...stylex.props(styles.row, index > 0 && styles.rowSeparated)}
+ data-step={item.key}
+ key={item.key}
+ >
+ <div {...stylex.props(styles.head)}>
+ <Flexbox horizontal align={'flex-start'} gap={12} style={{ minWidth: 0 }}>
+ <Text fontSize={13} {...stylex.props(styles.index)}>
+ {index + 1}
</Text>
- )}
- </Flexbox>
- </Flexbox>
+ <Flexbox gap={2} style={{ minWidth: 0 }}>
+ <Text weight={500}>{item.title}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {item.desc}
+ </Text>
+ {item.warning && (
+ <Text fontSize={12} type={'warning'}>
+ {item.warning}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ {item.action}
+ </div>
+ {renderField && item.fields && item.fields.length > 0 && (
+ <div {...stylex.props(styles.fields)}>
+ {item.fields.map((key) => (
+ <Fragment key={key}>{renderField(key)}</Fragment>
+ ))}
+ </div>
+ )}
+ </div>
))}
- </Flexbox>
+ </div>
);
});
diff --git a/src/features/AgentChannel/quickSetup/guides.ts b/src/features/AgentChannel/quickSetup/guides.ts
index de801c2b976..e9d4a4101d7 100644
--- a/src/features/AgentChannel/quickSetup/guides.ts
+++ b/src/features/AgentChannel/quickSetup/guides.ts
@@ -24,6 +24,12 @@ export type SetupLinkLabel =
| 'openSlackApp';
export interface SetupStep {
+ /**
+ * Keys of the credential fields this step is about (`applicationId`, or a key
+ * under `credentials`; `extras` is the platform's helper under them). While a bot is being set up they are filled in right
+ * under the step; a saved bot keeps them in its credentials group instead.
+ */
+ fields?: string[];
/** i18n: `channel.quickSetup.<guide>.<key>.title` / `.desc` (agent namespace). */
key: string;
link?: { href: string; label: SetupLinkLabel };
@@ -64,7 +70,11 @@ export const getSetupGuide = (
guide: 'feishu',
scanToCreate: true,
steps: [
- { key: 'create', link: { href: FEISHU_CONSOLE_URL[platformId], label: 'openConsole' } },
+ {
+ key: 'create',
+ fields: ['applicationId', 'appSecret'],
+ link: { href: FEISHU_CONSOLE_URL[platformId], label: 'openConsole' },
+ },
{ key: 'bot' },
{ key: 'events' },
{ key: 'publish' },
@@ -84,8 +94,16 @@ export const getSetupGuide = (
label: 'createSlackApp',
},
},
- { key: 'install', link: { href: appPage('oauth'), label: 'openSlackApp' } },
- { key: 'tokens', link: { href: appPage('general'), label: 'openSlackApp' } },
+ {
+ key: 'install',
+ fields: ['botToken'],
+ link: { href: appPage('oauth'), label: 'openSlackApp' },
+ },
+ {
+ key: 'tokens',
+ fields: ['applicationId', 'signingSecret', 'appToken'],
+ link: { href: appPage('general'), label: 'openSlackApp' },
+ },
],
};
}
@@ -94,9 +112,10 @@ export const getSetupGuide = (
guide: 'discord',
steps: [
{ key: 'create', link: { href: DISCORD_DEVELOPER_PORTAL_URL, label: 'openConsole' } },
- { key: 'credentials' },
+ { key: 'credentials', fields: ['applicationId', 'publicKey'] },
{
key: 'bot',
+ fields: ['botToken'],
link: {
href: appId ? buildDiscordBotPageUrl(appId) : DISCORD_DEVELOPER_PORTAL_URL,
label: 'openBotSettings',
@@ -115,7 +134,7 @@ export const getSetupGuide = (
guide: 'telegram',
steps: [
{ key: 'botfather', link: { href: TELEGRAM_BOTFATHER_URL, label: 'openBotFather' } },
- { key: 'token' },
+ { key: 'token', fields: ['botToken'] },
{ key: 'privacy' },
],
};
@@ -125,7 +144,7 @@ export const getSetupGuide = (
guide: 'qq',
steps: [
{ key: 'create', link: { href: QQ_BOT_CONSOLE_URL, label: 'openConsole' } },
- { key: 'credentials' },
+ { key: 'credentials', fields: ['applicationId', 'appSecret'] },
],
};
}
@@ -140,7 +159,13 @@ export const getSetupGuide = (
key: 'messagingApi',
link: { href: LINE_ACCOUNT_MANAGER_URL, label: 'openLineAccountManager' },
},
- { key: 'credentials', link: { href: LINE_CONSOLE_URL, label: 'openConsole' } },
+ {
+ key: 'credentials',
+ // `extras` is the platform's helper button ("Fetch from LINE"), which fills the
+ // destination user ID from the access token, so it follows the fields it needs.
+ fields: ['channelAccessToken', 'channelSecret', 'applicationId', 'extras'],
+ link: { href: LINE_CONSOLE_URL, label: 'openConsole' },
+ },
{ key: 'webhook' },
],
};
@@ -150,3 +175,22 @@ export const getSetupGuide = (
}
}
};
+
+/**
+ * Credential field keys a platform's setup steps fill in place. Empty for a
+ * platform without a guide, so its credentials stay in one group.
+ */
+export const getInlineFieldKeys = (platformId: string): Set<string> =>
+ new Set(
+ (getSetupGuide(platformId, { appName: '' })?.steps ?? []).flatMap((step) => step.fields ?? []),
+ );
+
+/**
+ * Where the "save and connect" step goes: right after the last step that asks for a credential,
+ * since everything after it (inviting the bot, turning on a webhook, subscribing to events) needs
+ * the bot to be saved and running. A guide whose steps ask for nothing gets it at the end.
+ */
+export const connectStepIndex = (steps: SetupStep[]): number => {
+ const last = steps.findLastIndex((step) => (step.fields?.length ?? 0) > 0);
+ return last === -1 ? steps.length : last + 1;
+};
diff --git a/src/features/AgentChannel/quickSetup/quickSetup.test.ts b/src/features/AgentChannel/quickSetup/quickSetup.test.ts
index 66b536562e8..9e8e250405c 100644
--- a/src/features/AgentChannel/quickSetup/quickSetup.test.ts
+++ b/src/features/AgentChannel/quickSetup/quickSetup.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { getSetupGuide } from './guides';
+import { connectStepIndex, getInlineFieldKeys, getSetupGuide } from './guides';
import {
buildDiscordInviteUrl,
buildSlackCreateAppUrl,
@@ -154,4 +154,38 @@ describe('getSetupGuide', () => {
it('has no guide for platforms with their own flow', () => {
expect(getSetupGuide('wechat', { appName: 'Moss' })).toBeUndefined();
});
+
+ it('asks for each credential in the step that produces it', () => {
+ const guide = getSetupGuide('discord', { appName: 'Moss' })!;
+ const fieldsOf = (key: string) => guide.steps.find((step) => step.key === key)?.fields;
+
+ expect(fieldsOf('credentials')).toEqual(['applicationId', 'publicKey']);
+ expect(fieldsOf('bot')).toEqual(['botToken']);
+ });
+
+ it('never asks for one credential in two steps', () => {
+ for (const platform of ['discord', 'slack', 'telegram', 'qq', 'line', 'feishu', 'lark']) {
+ const guide = getSetupGuide(platform, { appName: 'Moss' })!;
+ const keys = guide.steps.flatMap((step) => step.fields ?? []);
+
+ expect(new Set(keys).size).toBe(keys.length);
+ }
+ });
+
+ it('lists the inline credentials per platform, and none for a platform without a guide', () => {
+ expect([...getInlineFieldKeys('telegram')]).toEqual(['botToken']);
+ expect(getInlineFieldKeys('wechat').size).toBe(0);
+ });
+
+ it('asks to save right after the last step with a credential, before what needs a running bot', () => {
+ const at = (platform: string) => {
+ const steps = getSetupGuide(platform, { appName: 'Moss' })!.steps;
+ return steps.map((step) => step.key).toSpliced(connectStepIndex(steps), 0, 'connect');
+ };
+
+ expect(at('discord')).toEqual(['create', 'credentials', 'bot', 'connect', 'invite']);
+ expect(at('telegram')).toEqual(['botfather', 'token', 'connect', 'privacy']);
+ expect(at('line')).toEqual(['account', 'messagingApi', 'credentials', 'connect', 'webhook']);
+ expect(connectStepIndex([{ key: 'only' }])).toBe(1);
+ });
});
diff --git a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx
index 0a72aec4567..1a2bb85337b 100644
--- a/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx
+++ b/src/features/AgentSetting/AgentChannel/feishu/UserIdExtras.tsx
@@ -161,7 +161,7 @@ export const FeishuUserIdExtras = ({
icon={<Download size={14} />}
loading={loading}
size="small"
- style={{ alignSelf: 'flex-start', marginBlockEnd: 12, marginInlineStart: 32 }}
+ style={{ alignSelf: 'flex-start', marginBlockEnd: 12 }}
type="default"
onClick={handleClick}
>
diff --git a/src/routes/(main)/agent/channel/Header.tsx b/src/routes/(main)/agent/channel/Header.tsx
index 55dff7f954a..617bc46fe24 100644
--- a/src/routes/(main)/agent/channel/Header.tsx
+++ b/src/routes/(main)/agent/channel/Header.tsx
@@ -32,7 +32,6 @@ import NavHeader from '@/features/NavHeader';
import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
import { useAgentStore } from '@/store/agent';
import type { BotProviderItem } from '@/store/agent/slices/bot/action';
-import { BOT_RUNTIME_STATUSES, type BotRuntimeStatus } from '@/types/botRuntimeStatus';
import { resolveChannelHeaderView } from './headerView';
import { isImportableChannel, planChannelImport } from './importPlan';
@@ -47,17 +46,8 @@ interface HeaderProps {
/** Platform definitions are still loading. */
platformsLoading?: boolean;
providers?: BotProviderItem[];
- runtimeStatus?: BotRuntimeStatus;
}
-const STATUS_TAG_COLORS: Partial<Record<BotRuntimeStatus, string>> = {
- [BOT_RUNTIME_STATUSES.connected]: 'success',
- [BOT_RUNTIME_STATUSES.dormant]: 'warning',
- [BOT_RUNTIME_STATUSES.failed]: 'error',
- [BOT_RUNTIME_STATUSES.queued]: 'processing',
- [BOT_RUNTIME_STATUSES.starting]: 'processing',
-};
-
const Header = memo<HeaderProps>(
({
agentId,
@@ -67,7 +57,6 @@ const Header = memo<HeaderProps>(
platformId,
platformsLoading = false,
providers,
- runtimeStatus,
}) => {
const { t } = useTranslation(['agent', 'chat', 'common']);
const view = resolveChannelHeaderView(platformId, platformDef, platformsLoading);
@@ -224,31 +213,6 @@ const Header = memo<HeaderProps>(
[agentId, connectBot, currentConfig, disabled, t, updateBotProvider, writeDisabled],
);
- const statusLabel = (() => {
- switch (runtimeStatus) {
- case BOT_RUNTIME_STATUSES.connected: {
- return t('channel.statusConnected');
- }
- case BOT_RUNTIME_STATUSES.failed: {
- return t('channel.statusFailed');
- }
- case BOT_RUNTIME_STATUSES.queued: {
- return t('channel.statusQueued');
- }
- case BOT_RUNTIME_STATUSES.starting: {
- return t('channel.statusStarting');
- }
- case BOT_RUNTIME_STATUSES.dormant: {
- return t('channel.statusDormant');
- }
- case BOT_RUNTIME_STATUSES.disconnected: {
- return t('channel.statusDisconnected');
- }
- default: {
- return undefined;
- }
- }
- })();
const menuItems: DropdownItem[] = [];
if (platformDef?.documentation?.portalUrl) {
@@ -308,14 +272,6 @@ const Header = memo<HeaderProps>(
: t('channel.paidFeature.badge')}
</Tag>
)}
- {statusLabel && (
- <Tag
- color={runtimeStatus ? STATUS_TAG_COLORS[runtimeStatus] : undefined}
- size={'small'}
- >
- {statusLabel}
- </Tag>
- )}
{currentConfig?.enabled && (
<ActionIcon
disabled={writeDisabled}
diff --git a/src/routes/(main)/agent/channel/index.tsx b/src/routes/(main)/agent/channel/index.tsx
index 9c0dfdb6e2b..790d1ecbc91 100644
--- a/src/routes/(main)/agent/channel/index.tsx
+++ b/src/routes/(main)/agent/channel/index.tsx
@@ -76,9 +76,6 @@ const ChannelContent = memo(() => {
platformId={platform}
platformsLoading={platformsLoading}
providers={providers}
- runtimeStatus={
- activePlatformDef ? platformRuntimeStatuses.get(activePlatformDef.id) : undefined
- }
/>
<Flexbox flex={1} style={{ overflow: 'hidden' }}>
<AsyncBoundary
diff --git a/src/routes/(main)/agent/channel/permission.test.tsx b/src/routes/(main)/agent/channel/permission.test.tsx
index aa34e6228db..da95368cd08 100644
--- a/src/routes/(main)/agent/channel/permission.test.tsx
+++ b/src/routes/(main)/agent/channel/permission.test.tsx
@@ -8,7 +8,7 @@ import { describe, expect, it, vi } from 'vitest';
import PlatformDetail, { type ChannelFormValues } from '@/features/AgentChannel/PlatformDetail';
import Body from '@/features/AgentChannel/PlatformDetail/Body';
-import SaveBar from '@/features/AgentChannel/PlatformDetail/SaveBar';
+import { FooterActions } from '@/features/AgentChannel/PlatformDetail/Footer';
import type { SerializedPlatformDefinition } from '@/server/services/bot/platforms/types';
import Header from './Header';
@@ -220,27 +220,52 @@ const currentConfig = {
};
const BodyHarness = ({
+ activeTab,
disabled,
- hasConfig = true,
}: {
+ activeTab: 'advanced' | 'connect';
disabled?: boolean;
- hasConfig?: boolean;
}) => {
const form = useForm<ChannelFormValues>();
return (
<Body
- currentConfig={hasConfig ? currentConfig : undefined}
+ hasConfig
+ activeTab={activeTab}
+ currentConfig={currentConfig}
disabled={disabled}
form={form}
- hasConfig={hasConfig}
platformDef={platformDef}
- removeDisabled={disabled}
+ />
+ );
+};
+
+const FooterHarness = ({ disabled }: { disabled?: boolean }) => {
+ const form = useForm<ChannelFormValues>();
+
+ return (
+ <FooterActions
+ hasConfig
+ isDirty
+ connecting={false}
+ disabled={disabled}
+ form={form}
+ platformDef={platformDef}
+ saving={false}
+ testing={false}
+ writeDisabled={disabled}
+ onCopied={vi.fn()}
onDelete={vi.fn()}
+ onDiscard={vi.fn()}
+ onSave={vi.fn()}
+ onTestConnection={vi.fn()}
/>
);
};
+// A saved bot folds its credentials away; open them the way a person would.
+const openCredentials = () => fireEvent.click(screen.getByText('channel.credentials'));
+
describe('Agent channel permission gates', () => {
beforeEach(() => {
mocks.activeWorkspaceId = null;
@@ -248,93 +273,55 @@ describe('Agent channel permission gates', () => {
});
it('renders channel credentials as read-only when editing is denied', () => {
- render(<BodyHarness disabled />);
+ const { unmount } = render(<BodyHarness disabled activeTab="connect" />);
- expect(screen.getByRole('textbox', { name: /^channel\.applicationId/ })).toBeDisabled();
+ openCredentials();
+ expect(screen.getByRole('textbox', { name: /^channel.applicationId/ })).toBeDisabled();
expect(screen.queryByTestId('info-tooltip')).not.toBeInTheDocument();
expect(screen.getByLabelText('channel.botToken')).toBeDisabled();
- expect(screen.getByRole('textbox', { name: 'channel.charLimit' })).toBeDisabled();
- expect(screen.getByRole('button', { name: 'channel.settingsResetDefault' })).toBeDisabled();
- });
+ unmount();
- it('opens every settings section for a saved bot', () => {
- render(<BodyHarness />);
+ render(<BodyHarness disabled activeTab="advanced" />);
- expect(screen.getByText('channel.section.replies.title')).toBeInTheDocument();
- expect(screen.getByText('channel.section.account.title')).toBeInTheDocument();
- expect(screen.getByRole('textbox', { name: 'channel.charLimit' })).toBeInTheDocument();
- expect(screen.getByText('channel.applicationIdHint')).toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: /^channel.charLimit/ })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'channel.settingsResetDefault' })).toBeDisabled();
});
- it('folds settings sections until the bot is first saved, leading with the credentials', async () => {
- render(<BodyHarness hasConfig={false} />);
+ it('shows one tab at a time and keeps the others mounted', () => {
+ const { rerender } = render(<BodyHarness activeTab="advanced" />);
- expect(screen.getByRole('textbox', { name: /^channel\.applicationId/ })).toBeInTheDocument();
- expect(screen.queryByRole('textbox', { name: 'channel.charLimit' })).not.toBeInTheDocument();
- expect(screen.queryByRole('button', { name: 'channel.removeChannel' })).not.toBeInTheDocument();
+ expect(screen.getByRole('textbox', { name: /^channel.charLimit/ })).toBeInTheDocument();
+ expect(
+ screen.queryByRole('textbox', { name: /^channel.applicationId/ }),
+ ).not.toBeInTheDocument();
+ // The hidden panel is still in the document, so its values survive a save.
+ expect(document.querySelector('#channel-panel-connect')).toHaveAttribute('hidden');
- fireEvent.click(screen.getByRole('button', { name: /channel\.section\.replies\.title/ }));
- await waitFor(() =>
- expect(screen.getByRole('textbox', { name: 'channel.charLimit' })).toBeInTheDocument(),
- );
+ rerender(<BodyHarness activeTab="connect" />);
+
+ openCredentials();
+ expect(screen.getByRole('textbox', { name: /^channel.applicationId/ })).toBeInTheDocument();
+ expect(screen.queryByRole('textbox', { name: /^channel.charLimit/ })).not.toBeInTheDocument();
});
it('disables mutating channel actions when editing is denied', () => {
- render(<BodyHarness disabled />);
- expect(screen.getByRole('button', { name: 'channel.removeChannel' })).toBeDisabled();
+ render(<FooterHarness disabled />);
- render(
- <SaveBar
- hasConfig
- isDirty
- writeDisabled
- connecting={false}
- saving={false}
- onDiscard={vi.fn()}
- onSave={vi.fn()}
- />,
- );
+ expect(screen.getByRole('button', { name: 'channel.removeChannel' })).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'channel.testConnection' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'channel.discard' })).toBeDisabled();
expect(screen.getByRole('button', { name: 'channel.save' })).toBeDisabled();
});
- it('disables Test Connection for a read-only channel', async () => {
- render(
- <PlatformDetail
- disabled
- agentId="agent-id"
- currentConfig={currentConfig}
- platformDef={platformDef}
- />,
- );
-
- await waitFor(() =>
- expect(screen.getByRole('button', { name: 'channel.testConnection' })).toBeDisabled(),
- );
- });
-
- it('labels the first save as connecting the bot', () => {
- render(
- <SaveBar
- connecting={false}
- hasConfig={false}
- isDirty={false}
- saving={false}
- onDiscard={vi.fn()}
- onSave={vi.fn()}
- />,
- );
-
- expect(screen.getByRole('button', { name: 'channel.saveAndConnect' })).toBeEnabled();
- expect(screen.getByText('channel.saveBar.firstSave')).toBeInTheDocument();
- });
-
it('discards form edits and restores the persisted configuration', async () => {
render(
<PlatformDetail agentId="agent-id" currentConfig={currentConfig} platformDef={platformDef} />,
);
- const applicationId = screen.getByRole('textbox', { name: /^channel\.applicationId/ });
+ // A saved bot opens on its first settings tab; the app ID lives on "connect".
+ fireEvent.click(screen.getByRole('tab', { name: 'channel.tab.connect' }));
+ openCredentials();
+ const applicationId = screen.getByRole('textbox', { name: /^channel.applicationId/ });
await waitFor(() => expect(applicationId).toHaveValue('app-id'));
expect(screen.queryByRole('button', { name: 'channel.discard' })).not.toBeInTheDocument();
@@ -346,9 +333,7 @@ describe('Agent channel permission gates', () => {
);
screen.getByRole('button', { name: 'channel.discard' }).click();
await waitFor(() =>
- expect(screen.getByRole('textbox', { name: /^channel\.applicationId/ })).toHaveValue(
- 'app-id',
- ),
+ expect(screen.getByRole('textbox', { name: /^channel.applicationId/ })).toHaveValue('app-id'),
);
}, 15_000);
@@ -359,7 +344,6 @@ describe('Agent channel permission gates', () => {
agentId="agent-id"
currentConfig={currentConfig}
platformDef={platformDef}
- runtimeStatus="connected"
/>,
);
@@ -442,7 +426,7 @@ describe('Agent channel permission gates', () => {
expect(screen.getByRole('switch')).toBeDisabled();
});
- it('renders the paid-feature alert with the platform name', () => {
+ it('renders the paid-feature alert with the platform name and top spacing', () => {
render(
<PlatformDetail
agentId="agent-id"
@@ -462,6 +446,7 @@ describe('Agent channel permission gates', () => {
const alert = screen.getByTestId('channel-paid-alert');
expect(alert).toHaveTextContent('channel.paidFeature.notice.title:WeChat');
expect(alert).toHaveTextContent('channel.paidFeature.notice.desc.personal:WeChat');
+ expect(alert).toHaveStyle({ marginBlockStart: '16px' });
});
it('renders personal upgrade guidance and navigates to personal plans', async () => {