完整实现指南)
为 Novu Agent 接入新聊天频道Channel SetupGuideLayer-1 连接引导完整实现指南【免费下载链接】novuThe open-source communication infrastructure for agents and products项目地址: https://gitcode.com/GitHub_Trending/no/novu导读在 Novu 这个开源通信基础设施仓库中Agent 的聊天频道接入被拆成连接渠道本身与接入后的下一步引导两个层次。本文聚焦Layer 1连接引导如何在apps/dashboard前端中为一个新聊天频道如 Discord新增一套编号式SetupGuide引导开发者依次完成在渠道控制台创建应用/Bot → 在 Novu 保存凭证 → 安装/验证 → 发送首条消息并通过connectedAt轮询实现真实的Listening… / Connected 连接态检测。读完本文你将掌握这套组件的运行原理、可复用的基础构件primitives、完整文件清单与接线方式并能照葫芦画瓢实现自己的ChannelSetupGuide。本文对应仓库内文档 .cursor/skills/add-channel-setup-guide/SKILL.md 与配套模板 .cursor/skills/add-channel-setup-guide/reference.md全部实现证据均可在apps/dashboard/src/components/agents/下找到。1. 什么是 Layer-1 Setup Guide把连接和接入后分离开Novu Dashboard 的 Agent 集成引导被明确分成两层Layer 1本指南范围 连接渠道本身。开发者要做的动作是创建渠道应用/Bot → 在 Novu 里保存其凭证 → 安装/验证 → 向 Bot 发送第一条真实消息。UI 上表现为一个带编号的步骤条stepper同时有一个实时的Listening… / Connected状态指示。Layer 2 连接成功后的下一步引导如群发推广、用户开通等由独立的add-channel-whats-next-onboarding技能覆盖不在本文范围内。在运行时由resolve-agent-integration-guide.tsx决定渲染哪一屏当集成链接尚未建立真实连接时把对应的ChannelSetupGuide渲染为setup 视图一旦integrationLink.connectedAt被后端写入就切换到connected/whats next 视图见该文件isConnected Boolean(integrationLink.connectedAt)以及AgentIntegrationGuideTransition组件。所有 setup guide 都位于apps/dashboard/src/components/agents/。当前仓库中已存在的兄弟实现包括文件特点telegram-setup-guide.tsx最简实现三层步骤 二维码 webhook 注册 订阅者深链推荐作为新频道起点slack-setup-guide.tsx增加了 Quick/Manual 双路径SetupModeToggle与自动生成的 Slack manifestteams-setup-guide.tsx多凭证 Azure 流程sendblue-setup-guide.tsx、web-chat-setup-guide.tsx等各自频道的专属实现从resolve-agent-integration-guide.tsx的 setupswitch可以看到目前接线在案的频道有 Slack、MS Teams、Telegram、Sendblue没有专属 guide 的 chat provider 会回退到通用GenericAgentIntegrationGuide。2. 工作原理连接是被检测出来的不是被断言出来的原文档给出了这套引导的核心组件结构ChannelSetupGuide ├─ useFetchIntegrations() → find integration by _id providerId ├─ SetupStepperRail │ └─ SetupStep × N → create app · save creds · install/verify │ └─ SetupButton / IntegrationCredentialsSidebar trigger ├─ ListeningStatus → polls listAgentIntegrations every 1s; │ fires onConnected confetti when connectedAt is set └─ IntegrationCredentialsSidebar → generic credential save (useUpdateIntegration)需要反复强调的核心理念这也是整个 Layer-1 的灵魂Connection is detected, not asserted.一个渠道只有当前端真实收到首条入站消息、后端在该集成链接上写入connectedAt字段时才算已连接。 保存凭证、完成 OAuth/安装都并不代表已连接——这些必须各自作为独立的本地状态维护。源码佐证位于is-agent-integration-connected.ts/** Whether a real inbound message has landed (API stamped connectedAt). */ export function hasAgentInboundConnection(connectedAt: string | null | undefined): boolean { if (!connectedAt) { return false; } // … 解析时间戳并判断是否在合理窗口内短期时钟偏差容忍 } export function isAgentIntegrationConnected(link: PickAgentIntegrationLink, connectedAt): boolean { return hasAgentInboundConnection(link.connectedAt); }ListeningStatus在setup-guide-primitives.tsx中通过listAgentIntegrations每 1 秒轮询一次源码中setInterval(() void tick(), 1000)匹配l.integration._id watchedIntegrationId的链接一旦hasAgentInboundConnection(link.connectedAt)为真就触发彩带动画react-confetti1000 片10 秒后自动清理调用onConnected?.()通知父级把本地状态置为已连接、推进步骤条invalidateQueries({ queryKey: getAgentIntegrationsQueryKey(environment._id, agentIdentifier) })刷新服务端状态并停止轮询。轮询期间瞬时错误会被静默吞掉catch {}清理函数会正确清除 interval 与 confetti 定时器。3. 基础构件Building Blocksprimitives 与 step-utils原文档指出所有构件都来自setup-guide-primitives.tsx和setup-guide-step-utils.ts。逐一看一下它们在源码中的真实角色3.1setup-guide-primitives.tsx文件位于 apps/dashboard/src/components/agents/setup-guide-primitives.tsx导出以下符号符号源码中的角色SetupStepperRail垂直编号导轨内部是relative flex flex-col gap-10 pl-8在left-[22px]画一条带渐变的竖线顶部/底部淡出支持continuesAbove/continuesBelow用于让上下两根导轨在交界处保持线条连续ProviderSetupStepperRail就是continuesAbove的封装SetupStep单个步骤容器接收index、status、title、description、rightContent?、extraContent?、fullWidthContent?、headerSlot?、dimmed?、sectionLabel?、inlineSectionLabel?、indicator?等 props。dimmed会把整步降为 30% 不透明度并禁用指针事件indicatordot用于被动提示型步骤如 Whats-next 概览SetupButton次要描边按钮给了href就渲染成新标签页打开的a带noopener noreferrer与右上方箭头图标否则走onClick支持leadingIcon、disabledSetupModeToggleSetupModequick \| manualQuick Setup / Manual Setup 分段切换供 Slack 这类需要双路径的频道使用ReadOnlyValueRow只读、可一键复制的键值行用于手动 webhook 兜底面板展示回调 URL/密钥等IntegrationCredentialsSidebar基于IntegrationSheetIntegrationSettings的抽屉走useUpdateIntegration()保存 provider 凭证保存成功后showSuccessToast(Integration updated successfully)→onSaveSuccess?.()→onClose()。agentOnboarding模式下还会同步 URL 上的agent_onboardingtrue参数ListeningStatus见上一节每秒轮询 confetti onConnected3.2setup-guide-step-utils.ts文件位于 apps/dashboard/src/components/agents/setup-guide-step-utils.tsderiveStepStatus(stepIndex, firstIncompleteStep): StepStatus→ 返回completed | current | upcoming小于首个未完成步骤即为完成等于即为当前步大于即为未开始。hasIntegrationCredentials(credentials)→ 只要有一个字符串类型凭证字段非空即为真。源码特意排除了布尔字段secure、requireTls等因为它们的默认false不应被算作凭证已保存。工具还包含buildAgentWebhookUrl拼接 agent webhook 地址${agentApiBaseUrl}/v1/agents/${agentId}/webhook/${identifier}、buildImessageFallbackHref生成sms:深链以及针对 Sendblue/WhatsApp 的强校验函数——它们用于处理Webhook secret / verify token 由 Novu 自动生成不能算用户凭证这类边界。3.3 直接使用示例setup-guide-step-utils与 primitives 的组合使用可参考 telegram-setup-guide.tsxconst firstIncompleteStep useMemo(...)依据isConnected→isWebhookConfigured || isCredentialsSaved的顺序决定当前推进到第几步再对每个步骤调用deriveStepStatus(base i, firstIncompleteStep)。4. 动手实现文件清单与组件契约4.1 前提条件Step 0 — Prerequisitesnovu/shared中存在ChatProviderIdEnum.Channel枚举值且packages/providers中已存在该 provider。全新 provider 属于先问再做ask-first范畴不能跳过评审直接写前端。该集成能够被创建/选中——添加 provider流程会传给你一个integrationId。4.2 文件清单File checklist照抄最接近的兄弟文件后重命名完整模板见 .cursor/skills/add-channel-setup-guide/reference.md新建apps/dashboard/src/components/agents/channel-setup-guide.tsx默认导出ChannelSetupGuide编辑apps/dashboard/src/components/agents/agent-integration-guides/resolve-agent-integration-guide.tsx在 setup 的switch里渲染ChannelSetupGuide ... embedded /并设置setupDisplayName可选仅当该频道需要 webhook 注册 / 快速设置 / 订阅者链接等超出纯凭证保存的服务端动作时才在/api/agents或/api/integrations增加 provider 专属 server action。关于setupDisplayName连接引导全部完成后resolver 会把控制权交给由add-channel-whats-next-onboarding技能负责的 connected 视图。4.3 组件契约Component contract新组件的 props 签名统一为export type DiscordSetupGuideProps { agent: AgentResponse; // 来自 /api/agents 的 agent 实体 integrationId: string; // 选中集成的 Mongo _id stepOffset?: number; // 默认为 1 onStepsCompleted?: () void; embedded?: boolean; };stepOffset语义Overview 页面以更高的基数挂载该引导Slack 注释里记为2而 Integrations 详情页从1开始所以二者不能写死。embedded为真时去掉 Overview 外壳此时由 resolver 通过SetupGuideWithHeaderSetupGuideCard包裹。4.4 状态机State machine原文档规定实现必须遵循以下 6 步状态推进逻辑用useFetchIntegrations()按_id integrationId providerId ChatProviderIdEnum.Channel解析出selectedIntegration跟踪进度hasIntegrationCredentials(...)或本地布尔credentialsSavedLocally外加安装/已连接等标志位在useEffect([integrationId])里把这些本地状态全部重置换集成不泄漏进度令const base stepOffset据此算出firstIncompleteStep再为每个SetupStep调deriveStepStatus(stepIndex, firstIncompleteStep)在SetupStepperRail内渲染步骤列然后在pl-8容器里渲染ListeningStatus最后渲染IntegrationCredentialsSidebarListeningStatus.onConnected→ 标记已连接并调用onStepsCompleted?.()同时提供embedded返回无 Overview 外框供 resolver 用与独立渲染返回。5. 典型三步配方Typical 3-step recipe大多数聊天频道走同一个三步结构这也是为什么 Telegram 是最佳参照物Create the app/bot在渠道侧创建应用/BotSetupButton href跳转 provider 控制台。可选增强manifest用CodeBlock展示所有注入值都要转义或一个触发 server action 的快速设置输入框。Save credentials in Novu在 Novu 保存凭证SetupButton onClick{() setIsCredentialsSidebarOpen(true)}打开抽屉抽屉的onSaveSuccess回调把credentialsSavedLocally置真并可顺带触发 provider 专属动作如 webhook 注册。Install / verify send first message安装/验证并发送首条消息展示渠道侧连接按钮或可复制的指引文本由ListeningStatus盯着connectedAt一旦后端写入即宣告连接完成。参考模板中的第三步会用到降灰技巧当凭证尚未保存时把第三步设为dimmedopacity-30pointer-events-none避免开发者跳过前置步骤直接操作。6. 参照模板骨架一个可直接套用的channel-setup-guide.tsx以下骨架直接取自 reference.md以 Discord 为例Channel PascalCasechannel kebab-case。它是参考实现的最小完整版体现了上面全部的状态机与组件契约import { ChatProviderIdEnum } from novu/shared; import { useQueryClient } from tanstack/react-query; import { useCallback, useEffect, useMemo, useState } from react; import { RiKey2Line } from react-icons/ri; import type { AgentResponse } from /api/agents; import { useEnvironment } from /context/environment/hooks; import { useFetchIntegrations } from /hooks/use-fetch-integrations; import { IntegrationCredentialsSidebar, ListeningStatus, SetupButton, SetupStep, SetupStepperRail, } from ./setup-guide-primitives; import { deriveStepStatus, hasIntegrationCredentials } from ./setup-guide-step-utils; export type DiscordSetupGuideProps { agent: AgentResponse; integrationId: string; stepOffset?: number; onStepsCompleted?: () void; embedded?: boolean; }; export function DiscordSetupGuide({ agent, integrationId, stepOffset 1, onStepsCompleted, embedded false, }: DiscordSetupGuideProps) { const { currentEnvironment } useEnvironment(); const [isCredentialsSidebarOpen, setIsCredentialsSidebarOpen] useState(false); const [credentialsSavedLocally, setCredentialsSavedLocally] useState(false); const [isConnected, setIsConnected] useState(false); // Reset progress when the watched integration changes. useEffect(() { setIsConnected(false); setCredentialsSavedLocally(false); }, [integrationId]); const { integrations } useFetchIntegrations(); const selectedIntegration useMemo( () integrations?.find((i) i._id integrationId i.providerId ChatProviderIdEnum.Discord), [integrations, integrationId] ); const isCredentialsSaved hasIntegrationCredentials(selectedIntegration?.credentials) || credentialsSavedLocally; const base stepOffset; const firstIncompleteStep useMemo(() { if (isConnected) return base 2; if (isCredentialsSaved) return base 1; return base; }, [base, isCredentialsSaved, isConnected]); const handleConnected useCallback(() { setIsConnected(true); onStepsCompleted?.(); }, [onStepsCompleted]); const stepsColumn ( SetupStep index{base} status{deriveStepStatus(base, firstIncompleteStep)} titleCreate a Discord app and bot descriptionCreate an application in the Discord Developer Portal, add a bot, and copy its token. rightContent{SetupButton hrefhttps://discord.com/developers/applicationsOpen Discord Portal/SetupButton} / SetupStep index{base 1} status{deriveStepStatus(base 1, firstIncompleteStep)} titleSave the bot token in Novu descriptionOpen the credentials form and paste the bot token. rightContent{ SetupButton leadingIcon{RiKey2Line classNamesize-3.5 /} onClick{() setIsCredentialsSidebarOpen(true)} Configure credentials /SetupButton } / SetupStep index{base 2} status{deriveStepStatus(base 2, firstIncompleteStep)} dimmed{!isCredentialsSaved} titleSend a test message descriptionMessage your bot on Discord — your agent should respond. / / ); const listening ( ListeningStatus agentIdentifier{agent.identifier} watchedIntegrationId{integrationId} onConnected{handleConnected} connectedMessageDiscord is connected — your agent is ready to receive messages. listeningMessageSend a message to your bot on Discord to finish connecting. / ); const sidebar ( IntegrationCredentialsSidebar integrationId{integrationId} isOpen{isCredentialsSidebarOpen} onClose{() setIsCredentialsSidebarOpen(false)} onSaveSuccess{() setCredentialsSavedLocally(true)} agentOnboarding / ); if (embedded) { return ( div classNameflex flex-col gap-0 SetupStepperRail classNamepy-6 pb-3 pr-3 md:pr-6{stepsColumn}/SetupStepperRail div classNamepl-8{listening}/div {sidebar} /div ); } return ( SetupStepperRail{stepsColumn}/SetupStepperRail div classNamepl-8{listening}/div {sidebar} / ); }7. 按需扩展可选的 add-ons来自现有频道的真实经验① Quick vs Manual 双路径参考 Slack。增加const [setupMode, setSetupMode] useStateSetupMode(quick)渲染SetupModeToggle mode{setupMode} onChange{setSetupMode} /Slack 的实现用 feature flag 控制是否展示然后在quick与manual两套stepsColumn变体之间切换。② 自动生成 manifest参考 Slack。拼一个 YAML 字符串必须转义双引号包裹的值用CodeBlock languageshell title…-manifest.yaml /放进fullWidthContent并把 manifest 放进 provider 控制台深链的 query string。Slack 的真实实现里就有escapeYamlDoubleQuoted先转\再转以及sanitizeBotDisplayNameSlack 会拒绝名称里含保留词 slack 的应用见 slack-setup-guide.tsxfunction escapeYamlDoubleQuoted(value: string): string { return value.replace(/\\/g, \\\\).replace(//g, \\); }Slack manifest 的settings.event_subscriptions.request_url与interactivity.request_url都指向同一 webhook 地址${agentApiBaseUrl}/v1/agents/${agentId}/webhook/${identifier}OAuth redirect 则指向/v1/integrations/chat/oauth/callback。③ Provider server action参考 Telegram/Slack。凭证保存后通过useMutation调用/api/agents或/api/integrations的辅助函数注册 webhook、快速设置、签发订阅者深链成功后执行queryClient.invalidateQueries({ queryKey: getAgentIntegrationsQueryKey(currentEnvironment?._id, agent.identifier), });把它挂在抽屉的onSaveSuccess上。以 telegram-setup-guide.tsx 为例onSaveSuccess同时做了三件事setCredentialsSavedLocally(true)、调用configureTelegram()注册 webhook、用configuredWebhookUrlbotUsername落地结果失败时通过InlineToast展示Webhook registration failed。④ 嵌入式凭证增强参考 Telegram。IntegrationCredentialsSidebar接受agentIdentifier与testSubscriberId用于渲染 provider 专属粘贴 UITelegram 的手机端设置二维码以及自定义submitLabelTelegram 用Save Connect。testSubscriberId在源码里取自currentUser._id——webhook 注册成功后组件会自动为当前登录用户签发一条订阅者深链requestTelegramSubscriberLink让第三步发测试消息能直接关联到测试订阅者。8. 接线到 resolver让引导出现在正确的位置完成ChannelSetupGuide后编辑 resolve-agent-integration-guide.tsx在setupswitch中追加分支connected 视图的接线由add-channel-whats-next-onboarding负责import { DiscordSetupGuide } from /components/agents/discord-setup-guide; case ChatProviderIdEnum.Discord: setupGuide DiscordSetupGuide agent{agent} integrationId{integrationLink.integration._id} embedded /; setupDisplayName Discord; break;注意该文件的switch内没有default而是通过setupGuide是否为空来判断——若没有专属 guide 就回退到GenericAgentIntegrationGuide。因此新频道一定要落在具体case上而不是依赖兜底。对照现有分支可以看到接入switch时实际传入的是integrationLink.integration._id集成链接中携带的集成实体的_id同时始终使用embedded去掉 Overview 外框让 resolver 自己的 Header SetupGuideCard 统一包装并展示Action needed/Connected徽标。完整接线清单Worked example — DiscordPrereqs: ChatProviderIdEnum.Discord exists · Discord provider in packages/providers. Create: apps/dashboard/src/components/agents/discord-setup-guide.tsx Edit: agent-integration-guides/resolve-agent-integration-guide.tsx (setup-switch case, import) Verify: open a non-connected Discord integration → 3 steps, save token via drawer, Listening… → Connected on first inbound message. Types via diagnostics.9. 约定与易错点Conventions gotchas原文档沉淀的经验全部能被源码佐证installed/credentialed 与 connected 是三种互相独立的状态只有connectedAt能推进最后一步。Slack 的实现把isSlackAppInstalledOAuth 完成与工作区已连接收到首条真实消息严格分开。不要给凭证保存或 OAuth 完成回调接上onConnected——那只会制造假连接。服务端状态走 TanStack Query任何 mutation 之后都 invalidategetAgentIntegrationsQueryKey(currentEnvironment?._id, agent.identifier)ListeningStatus内部也会在检测到connectedAt后做同样的事。manifest/代码片段里注入的值必须转义如 Slack YAML 双引号字符串。切换集成要重置本地状态integrationId变化时清空isConnected、credentialsSavedLocally等避免换一个集成把上一个的进度带过来。遵循 Novu / Dashboard 前端约定用type而非interface声明 props、具名导出、每个return前留空行、禁止嵌套三元表达式、动画从motion/react引入。开发时不启动 Dashboard4201 端口只通过 Cursor diagnostics 检查类型。10. 构建与验证Build verify原文档强调不要启动 dashboard 去验证避免拖慢开发循环。正确路径是只通过 Cursor diagnostics 检查类型从 Agent 的 Integrations 标签页添加/打开一个Channel集成人工确认保存凭证后步骤条能正确推进凭证抽屉能正常打开/保存保存成功后 toast Integration updated successfully状态从Listening…翻转为Connected并伴随彩带动画前提是一条真实消息已送达后端已写入connectedAt。11. 结语这套设计的可复用价值从架构视角看Novu 把每个渠道都长得不一样的接入体验收敛成了三样东西一套可视化步进原语SetupStepperRail/SetupStep/SetupButton、一条统一的凭证保存链路IntegrationCredentialsSidebaruseUpdateIntegration、一个不区分渠道的连接探针ListeningStatusconnectedAt。新增一个聊天频道的前端引导本质上就是在 Telegram/Slack 骨架之上替换三件事步骤文案与跳转链接、凭证抽屉的打开时机、以及可选的 provider server action。如果需要在接入后进一步编排用户开通/群发等下一步请参考本文开头提到的 Layer-2 技能与 resolver 中 connected 视图的分支结构如SlackAgentConnectedDetails、TelegramAgentConnectedDetails它们与 Layer-1 的switch是同一份组件树的两半。【免费下载链接】novuThe open-source communication infrastructure for agents and products项目地址: https://gitcode.com/GitHub_Trending/no/novu创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考