diff --git a/frontend/src/api/agent/index.ts b/frontend/src/api/agent/index.ts index bad055d8..c2cda726 100644 --- a/frontend/src/api/agent/index.ts +++ b/frontend/src/api/agent/index.ts @@ -262,6 +262,28 @@ export function listIMChannels(agentId: string) { return get<{ data: IMChannel[] }>(`/api/v1/agents/${agentId}/im-channels`); } +// Tenant-wide overview row. Credentials are intentionally omitted — use +// listIMChannels(agentId) when you need to edit a specific channel. +export interface IMChannelOverview { + id: string; + tenant_id: number; + agent_id: string; + agent_name: string; // empty string for built-in agents + platform: IMChannel['platform']; + name: string; + enabled: boolean; + mode: IMChannel['mode']; + output_mode: IMChannel['output_mode']; + session_mode?: IMChannel['session_mode']; + bot_identity: string; + created_at: string; + updated_at: string; +} + +export function listAllIMChannels() { + return get<{ data: IMChannelOverview[] }>('/api/v1/im-channels'); +} + export function createIMChannel(agentId: string, data: Partial) { return post<{ data: IMChannel }>(`/api/v1/agents/${agentId}/im-channels`, data); } diff --git a/frontend/src/assets/img/im/dingtalk.svg b/frontend/src/assets/img/im/dingtalk.svg new file mode 100644 index 00000000..73a26867 --- /dev/null +++ b/frontend/src/assets/img/im/dingtalk.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/assets/img/im/feishu.svg b/frontend/src/assets/img/im/feishu.svg new file mode 100644 index 00000000..b01ea259 --- /dev/null +++ b/frontend/src/assets/img/im/feishu.svg @@ -0,0 +1 @@ + diff --git a/frontend/src/assets/img/im/mattermost.svg b/frontend/src/assets/img/im/mattermost.svg new file mode 100644 index 00000000..d40cac04 --- /dev/null +++ b/frontend/src/assets/img/im/mattermost.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/assets/img/im/slack.svg b/frontend/src/assets/img/im/slack.svg new file mode 100644 index 00000000..2eb528db --- /dev/null +++ b/frontend/src/assets/img/im/slack.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/assets/img/im/telegram.svg b/frontend/src/assets/img/im/telegram.svg new file mode 100644 index 00000000..53458c55 --- /dev/null +++ b/frontend/src/assets/img/im/telegram.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/assets/img/im/wechat.svg b/frontend/src/assets/img/im/wechat.svg new file mode 100644 index 00000000..17a81888 --- /dev/null +++ b/frontend/src/assets/img/im/wechat.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/assets/img/im/wecom.svg b/frontend/src/assets/img/im/wecom.svg new file mode 100644 index 00000000..ab499fb9 --- /dev/null +++ b/frontend/src/assets/img/im/wecom.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/src/components/IMChannelsOverviewPanel.vue b/frontend/src/components/IMChannelsOverviewPanel.vue new file mode 100644 index 00000000..ef18376f --- /dev/null +++ b/frontend/src/components/IMChannelsOverviewPanel.vue @@ -0,0 +1,393 @@ + + + + + diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index fe44eeff..e0a022e6 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -47,6 +47,25 @@ {{ $t('settings.apiInfo') }} + + + + +
+ +
+
@@ -116,6 +154,8 @@ import { useAuthStore } from '@/stores/auth' import { MessagePlugin } from 'tdesign-vue-next' import { getCurrentUser, logout as logoutApi } from '@/api/auth' import { useI18n } from 'vue-i18n' +import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue' +import { listAllIMChannels, type IMChannelOverview } from '@/api/agent' const { t } = useI18n() @@ -124,7 +164,12 @@ const uiStore = useUIStore() const authStore = useAuthStore() const menuRef = ref() +const imMenuItemRef = ref() const menuVisible = ref(false) +const imSubmenuOpen = ref(false) +const imSubmenuStyle = ref>({}) +const hasActiveIMChannels = ref(false) +let imSubmenuHideTimer: ReturnType | null = null // 用户信息 const userInfo = ref({ @@ -168,6 +213,81 @@ const handleSettings = () => { router.push('/platform/settings') } +// Hover-driven submenu controls. A small hide delay tolerates the pointer +// slipping off briefly onto the gap between menu item and submenu pane. +const showIMSubmenu = () => { + if (imSubmenuHideTimer) { + clearTimeout(imSubmenuHideTimer) + imSubmenuHideTimer = null + } + // Compute panel position based on the menu item's rect — the panel is + // teleported to body so we can't rely on CSS `left: 100%`. + positionIMSubmenu() + imSubmenuOpen.value = true +} + +const scheduleHideIMSubmenu = () => { + if (imSubmenuHideTimer) clearTimeout(imSubmenuHideTimer) + imSubmenuHideTimer = setTimeout(() => { + imSubmenuOpen.value = false + imSubmenuHideTimer = null + }, 180) +} + +const closeAll = () => { + imSubmenuOpen.value = false + menuVisible.value = false +} + +// Silent prefetch so the "live" indicator on the IM menu item reflects reality +// as soon as the user sees the avatar area. Errors are swallowed — the +// indicator just stays off if the request fails, which is the conservative +// default. The panel component emits channels-changed after toggle/refresh so +// we stay in sync without re-polling. +const refreshIMStatus = async () => { + try { + const resp = await listAllIMChannels() + const data: IMChannelOverview[] = resp?.data || [] + hasActiveIMChannels.value = data.some((c) => c.enabled) + } catch { + // Intentionally ignored — indicator just stays off. + } +} + +const onChannelsChanged = (channels: IMChannelOverview[]) => { + hasActiveIMChannels.value = channels.some((c) => c.enabled) +} + +// Anchor the floating submenu just to the right of the hovered menu item, +// clamped to the viewport so it stays visible near the screen edge. +const positionIMSubmenu = () => { + const el = imMenuItemRef.value + if (!el) return + const rect = el.getBoundingClientRect() + const PANEL_WIDTH = 300 + const PANEL_MAX_HEIGHT = 520 + const GAP = 8 + const MARGIN = 8 + + let left = rect.right + GAP + // If the panel would overflow the right edge, flip to the left side. + if (left + PANEL_WIDTH + MARGIN > window.innerWidth) { + left = Math.max(MARGIN, rect.left - PANEL_WIDTH - GAP) + } + + // Align the panel's top with the menu item, then clamp so it doesn't + // spill past the bottom of the viewport. + let top = rect.top - 4 + const maxTop = window.innerHeight - Math.min(PANEL_MAX_HEIGHT, window.innerHeight - MARGIN * 2) - MARGIN + if (top > maxTop) top = maxTop + if (top < MARGIN) top = MARGIN + + imSubmenuStyle.value = { + left: `${left}px`, + top: `${top}px`, + } +} + const CHROME_EXTENSION_URL = 'https://chromewebstore.google.com/detail/jpemjbopikggjlmikmclgbmkhhopjdgd?utm_source=item-share-cb' @@ -252,14 +372,20 @@ const loadUserInfo = async () => { // 点击外部关闭菜单 const handleClickOutside = (e: MouseEvent) => { - if (menuRef.value && !menuRef.value.contains(e.target as Node)) { - menuVisible.value = false - } + const target = e.target as Node + if (menuRef.value && menuRef.value.contains(target)) return + // The submenu is teleported to body, so it's not inside menuRef — check it + // separately to avoid closing the dropdown when the user clicks the submenu. + const floating = document.querySelector('.im-submenu-floating') + if (floating && floating.contains(target)) return + menuVisible.value = false + imSubmenuOpen.value = false } onMounted(() => { document.addEventListener('click', handleClickOutside) loadUserInfo() + refreshIMStatus() }) onUnmounted(() => { @@ -411,6 +537,69 @@ onUnmounted(() => { } } + // 包含右弹子菜单的菜单项 + &--submenu { + position: relative; + + .menu-item-label { + flex: 1; + } + + .menu-chevron { + font-size: 14px; + color: var(--td-text-color-placeholder); + flex-shrink: 0; + transition: transform 0.15s; + } + + &.is-open { + background: var(--td-bg-color-container-hover); + + .menu-chevron { + color: var(--td-text-color-secondary); + } + } + + // "Live" indicator — shown when at least one IM channel is enabled. + // A small green dot with a halo that pulses to signal active connections. + .live-indicator { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + width: 10px; + height: 10px; + margin-right: 2px; + flex-shrink: 0; + } + + .live-indicator-dot { + position: relative; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--td-success-color, #07c160); + + // Pulsing halo around the dot. Prefers-reduced-motion disables it. + &::after { + content: ''; + position: absolute; + inset: -3px; + border-radius: 50%; + background: var(--td-success-color, #07c160); + opacity: 0.45; + animation: im-live-pulse 1.6s ease-out infinite; + pointer-events: none; + } + } + + @media (prefers-reduced-motion: reduce) { + .live-indicator-dot::after { + animation: none; + } + } + } + .menu-icon { font-size: 16px; color: var(--td-text-color-secondary); @@ -506,5 +695,35 @@ onUnmounted(() => { opacity: 1; transform: translateY(0); } + +// Live indicator halo animation — a soft expanding ring to signal that at +// least one IM channel is actively connected. +@keyframes im-live-pulse { + 0% { + transform: scale(0.9); + opacity: 0.45; + } + 70% { + transform: scale(1.8); + opacity: 0; + } + 100% { + transform: scale(1.8); + opacity: 0; + } +} + + + diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index faa77f80..b708a9ed 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -3979,4 +3979,29 @@ export default { syncResultDeleted: '-{n}', moreActions: 'More', }, + imOverview: { + menuTitle: 'Connected IMs', + pageTitle: 'Connected IMs', + subtitle: 'All IM channels connected to agents in this tenant — toggle state or jump to the owning agent', + totalCount: '{count} total', + empty: 'This tenant has no IM bots configured yet', + loadFailed: 'Failed to load IM bots', + builtinAgent: 'Built-in agent', + liveIndicator: 'IM channels are live', + detailsTitle: 'IM Bot Details', + gotoAgentEditor: 'Open in agent editor', + outputMode: 'Output mode', + sessionMode: 'Session mode', + updatedAt: 'Updated at', + channelId: 'Channel ID', + columns: { + platform: 'Platform', + name: 'Name', + agent: 'Agent', + mode: 'Mode', + enabled: 'Enabled', + botIdentity: 'Bot identity', + createdAt: 'Created at', + }, + }, } diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 1200a1ac..0991c431 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -4047,4 +4047,30 @@ export default { syncResultUpdated: "~{n}", syncResultDeleted: "-{n}", }, + imOverview: { + menuTitle: "연결된 IM", + pageTitle: "연결된 IM", + subtitle: "이 테넌트의 에이전트에 연결된 모든 IM 채널 — 활성화/비활성화 전환 또는 해당 에이전트로 이동", + totalCount: "총 {count}개", + empty: "이 테넌트에 구성된 IM 봇이 없습니다", + loadFailed: "IM 봇 목록을 불러오지 못했습니다", + builtinAgent: "내장 에이전트", + liveIndicator: "활성화된 IM 채널이 실행 중입니다", + liveIndicator: "활성화된 IM 채널이 실행 중입니다", + detailsTitle: "IM 봇 상세", + gotoAgentEditor: "에이전트 편집기에서 열기", + outputMode: "출력 모드", + sessionMode: "세션 모드", + updatedAt: "업데이트 시각", + channelId: "채널 ID", + columns: { + platform: "플랫폼", + name: "이름", + agent: "에이전트", + mode: "모드", + enabled: "활성화", + botIdentity: "봇 식별자", + createdAt: "생성 시각", + }, + }, }; diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 80ac774d..380b543f 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -3947,4 +3947,29 @@ export default { syncResultUpdated: '~{n}', syncResultDeleted: '-{n}', }, + imOverview: { + menuTitle: 'Подключённые IM', + pageTitle: 'Подключённые IM', + subtitle: 'Все IM-каналы агентов этого арендатора — переключение состояния или переход к владеющему агенту', + totalCount: 'Всего: {count}', + empty: 'В этом арендаторе пока не настроены IM-боты', + loadFailed: 'Не удалось загрузить список IM-ботов', + builtinAgent: 'Встроенный агент', + liveIndicator: 'IM-каналы работают', + detailsTitle: 'Детали IM-бота', + gotoAgentEditor: 'Открыть в редакторе агента', + outputMode: 'Режим вывода', + sessionMode: 'Режим сессии', + updatedAt: 'Обновлено', + channelId: 'ID канала', + columns: { + platform: 'Платформа', + name: 'Имя', + agent: 'Агент', + mode: 'Режим', + enabled: 'Включено', + botIdentity: 'Идентификатор бота', + createdAt: 'Создано', + }, + }, } diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 7fecf219..0c76e6e0 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -3976,4 +3976,29 @@ export default { syncResultDeleted: "-{n}", moreActions: "更多", }, + imOverview: { + menuTitle: "已接入的 IM", + pageTitle: "已接入的 IM", + subtitle: "当前租户下所有智能体已接入的 IM 渠道,可快速启停或跳转到对应智能体", + totalCount: "共 {count} 个", + empty: "当前租户还没有配置 IM 机器人", + loadFailed: "加载 IM 机器人列表失败", + builtinAgent: "内置智能体", + liveIndicator: "有已启用的 IM 渠道正在运行", + detailsTitle: "IM 机器人详情", + gotoAgentEditor: "前往 Agent 编辑", + outputMode: "输出模式", + sessionMode: "会话模式", + updatedAt: "更新时间", + channelId: "渠道 ID", + columns: { + platform: "平台", + name: "名称", + agent: "所属智能体", + mode: "模式", + enabled: "启用", + botIdentity: "Bot 标识", + createdAt: "创建时间", + }, + }, }; diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue index b59da41e..c0e8a662 100644 --- a/frontend/src/views/agent/AgentList.vue +++ b/frontend/src/views/agent/AgentList.vue @@ -715,6 +715,19 @@ const checkAndOpenEditModal = () => { } } +// Also re-run when the query mutates while this view is already mounted — +// e.g. the IM overview dialog navigating here via router.push lands on the +// same route, so onMounted alone never fires and the editor would only open +// after a manual refresh. +watch( + () => route.query.edit, + (v) => { + if (v && agents.value.length > 0) { + checkAndOpenEditModal() + } + }, +) + // 监听菜单创建智能体事件 const handleOpenAgentEditor = (event: CustomEvent) => { if (event.detail?.mode === 'create') { diff --git a/internal/handler/im.go b/internal/handler/im.go index 5813a6dc..f36a83e2 100644 --- a/internal/handler/im.go +++ b/internal/handler/im.go @@ -134,6 +134,26 @@ func (h *IMHandler) ListIMChannels(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"data": channels}) } +// ListAllIMChannels lists every IM channel in the current tenant, across +// agents, for the cross-agent overview page. Credentials are intentionally +// NOT included in the response — callers that need credentials must use the +// per-agent endpoint (GET /agents/:id/im-channels). +func (h *IMHandler) ListAllIMChannels(c *gin.Context) { + tenantID, ok := c.Request.Context().Value(types.TenantIDContextKey).(uint64) + if !ok { + c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"}) + return + } + + channels, err := h.imService.ListChannelsByTenant(tenantID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list channels"}) + return + } + + c.JSON(http.StatusOK, gin.H{"data": channels}) +} + // UpdateIMChannel updates an IM channel. func (h *IMHandler) UpdateIMChannel(c *gin.Context) { channelID := c.Param("id") diff --git a/internal/im/service.go b/internal/im/service.go index 734e2beb..c94df9db 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -2058,6 +2058,48 @@ func (s *Service) ListChannelsByAgent(agentID string, tenantID uint64) ([]IMChan return channels, nil } +// ChannelWithAgent augments an IMChannel summary with its owning agent's display name. +// Credentials are intentionally omitted so this type is safe to return from a +// tenant-scoped list endpoint; callers that need credentials must use the +// per-agent endpoint which enforces the same tenant scope anyway. +type ChannelWithAgent struct { + ID string `json:"id"` + TenantID uint64 `json:"tenant_id"` + AgentID string `json:"agent_id"` + AgentName string `json:"agent_name"` + Platform string `json:"platform"` + Name string `json:"name"` + Enabled bool `json:"enabled"` + Mode string `json:"mode"` + OutputMode string `json:"output_mode"` + SessionMode string `json:"session_mode"` + BotIdentity string `json:"bot_identity"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// ListChannelsByTenant returns all non-deleted IM channels in the given tenant, +// joined with custom_agents.name. Built-in agent IDs (whose rows may not exist +// in custom_agents) produce an empty AgentName — the frontend can substitute a +// localized "builtin agent" label in that case. +func (s *Service) ListChannelsByTenant(tenantID uint64) ([]ChannelWithAgent, error) { + var rows []ChannelWithAgent + err := s.db.Table("im_channels AS c"). + Select(`c.id, c.tenant_id, c.agent_id, + COALESCE(a.name, '') AS agent_name, + c.platform, c.name, c.enabled, c.mode, c.output_mode, + c.session_mode, c.bot_identity, c.created_at, c.updated_at`). + Joins(`LEFT JOIN custom_agents AS a + ON a.id = c.agent_id AND a.tenant_id = c.tenant_id`). + Where("c.tenant_id = ? AND c.deleted_at IS NULL", tenantID). + Order("c.created_at DESC"). + Scan(&rows).Error + if err != nil { + return nil, err + } + return rows, nil +} + // CreateChannel creates a new IM channel and optionally starts it. // Returns a duplicate_bot error if the bot identity is already used by another channel. func (s *Service) CreateChannel(channel *IMChannel) error { diff --git a/internal/router/router.go b/internal/router/router.go index aa15a44c..cd10ea68 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -676,6 +676,7 @@ func RegisterIMChannelRoutes(r *gin.RouterGroup, imHandler *handler.IMHandler) { // Channel operations by channel ID channels := r.Group("/im-channels") { + channels.GET("", imHandler.ListAllIMChannels) channels.PUT("/:id", imHandler.UpdateIMChannel) channels.DELETE("/:id", imHandler.DeleteIMChannel) channels.POST("/:id/toggle", imHandler.ToggleIMChannel)