diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts index ad96b2d5..ff5b1c8d 100644 --- a/frontend/src/api/chat/index.ts +++ b/frontend/src/api/chat/index.ts @@ -6,8 +6,12 @@ export async function createSessions(data = {}) { return post("/api/v1/sessions", data); } -export async function getSessionsList(page: number, page_size: number) { - return get(`/api/v1/sessions?page=${page}&page_size=${page_size}`); +export async function getSessionsList(page: number, page_size: number, source?: string) { + const params = new URLSearchParams({ page: String(page), page_size: String(page_size) }); + if (source) { + params.set("source", source); + } + return get(`/api/v1/sessions?${params.toString()}`); } export async function pinSession(session_id: string) { diff --git a/frontend/src/components/SourceSwitcherDropdown.vue b/frontend/src/components/SourceSwitcherDropdown.vue new file mode 100644 index 00000000..adda0393 --- /dev/null +++ b/frontend/src/components/SourceSwitcherDropdown.vue @@ -0,0 +1,163 @@ + + + + + diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index fc5cf564..68d6613f 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -94,6 +94,14 @@ class="menu-pending-badge" :title="t('organization.settings.pendingJoinRequestsBadge')">{{ orgStore.totalPendingJoinRequestCount }} + + + + + + @@ -138,6 +146,10 @@ + + @@ -175,6 +187,15 @@ import { onMounted, watch, computed, ref, h } from 'vue'; import { useRoute, useRouter } from 'vue-router'; import { getSessionsList, delSession, batchDelSessions, deleteAllSessions, clearSessionMessages, pinSession, unpinSession } from "@/api/chat/index"; import { useChatResourcesStore } from '@/stores/chatResources'; +import { listAllIMChannels } from '@/api/agent/index'; +import SourceSwitcherDropdown from './SourceSwitcherDropdown.vue'; +import { + DEFAULT_SESSION_SOURCE, + buildSourceOptions, + configuredPlatforms, + shouldShowSourceFilter, + type SessionSource, +} from './sessionSourceFilter'; import { logout as logoutApi } from '@/api/auth'; import { useMenuStore } from '@/stores/menu'; import { useAuthStore } from '@/stores/auth'; @@ -228,8 +249,25 @@ const currentpath = ref(''); const currentPage = ref(1); const page_size = ref(30); const total = ref(0); +// Monotonic token to discard stale list responses when loads race (see getMessageList). +let listRequestToken = 0; const currentSecondpath = ref(''); const scrollContainer = ref(null); +// Default to the user's own web chats; only tenants with a configured IM +// channel get the switcher to reach a platform's sessions. +const currentSource = ref(DEFAULT_SESSION_SOURCE); +const imPlatforms = ref([]); +const showSourceFilter = computed(() => shouldShowSourceFilter(imPlatforms.value)); +// Options for the source switcher: web first, then each configured IM platform. +// Logos are resolved here (where platformLogo lives) so the dropdown stays dumb. +const sourceOptions = computed(() => + buildSourceOptions(imPlatforms.value, t('menu.myChats'), (p) => t(`agentEditor.im.${p}`)) + .map((o) => ({ ...o, logo: o.platform ? platformLogo(o.platform) : '' })) +); +// Full label of the active source, shown as the trigger icon's tooltip. +const currentSourceLabel = computed(() => + sourceOptions.value.find((o) => o.value === currentSource.value)?.label ?? t('menu.myChats') +); // 计算总页数 const totalPages = computed(() => Math.ceil(total.value / page_size.value)); const hasMore = computed(() => currentPage.value < totalPages.value); @@ -641,8 +679,10 @@ const checkScrollBottom = () => { } const handleScroll = debounce(checkScrollBottom, 200) const getMessageList = async (isLoadMore = false) => { - if (loading.value) return Promise.resolve(); - loading.value = true; + // Scroll-driven load-more must never stack. A fresh load (first load, route + // change, or source switch) instead supersedes any in-flight request via the + // token below, so it is allowed through even while one is still running. + if (isLoadMore && loading.value) return Promise.resolve(); // 只有在首次加载或路由变化时才清空数组,滚动加载时不清空 if (!isLoadMore) { @@ -650,9 +690,16 @@ const getMessageList = async (isLoadMore = false) => { usemenuStore.clearMenuArr(); } - return getSessionsList(currentPage.value, page_size.value).then((res: any) => { + // Snapshot the source and claim a request token: when loads race, only the + // newest may mutate the list, so a slow earlier response can't append rows + // to the wrong source or revive a list the user has already switched away from. + const requestSource = currentSource.value; + const token = ++listRequestToken; + loading.value = true; + + return getSessionsList(currentPage.value, page_size.value, requestSource).then((res: any) => { + if (token !== listRequestToken) return; // superseded by a newer load if (res.data && res.data.length) { - // Display all sessions globally without filtering res.data.forEach((item: any) => { let obj = { title: item.title ? item.title : t('menu.newSession'), @@ -669,11 +716,14 @@ const getMessageList = async (isLoadMore = false) => { usemenuStore.updatemenuArr(obj) }); } - if ((res as any).total) { - total.value = (res as any).total; + // Use != null so an empty source (total === 0) correctly clears the count + // instead of leaving the previous source's total behind. + if (res && res.total != null) { + total.value = res.total; } loading.value = false; }).catch(() => { + if (token !== listRequestToken) return; // a newer load now owns `loading` loading.value = false; }) } @@ -693,6 +743,27 @@ async function loadCurrentKbInfo(kbId: string) { } } +// Switch the session source filter. getMessageList(false) resets pagination and +// clears the list itself, and its request token makes any in-flight load for the +// previous source a no-op, so the switch always lands on the chosen source. +const switchSource = (source: SessionSource) => { + if (source === currentSource.value) return; + currentSource.value = source; + getMessageList(); +}; + +// Detect whether this tenant has any IM channel configured. The filter control +// is only shown when it does, so non-IM users see an unchanged sidebar. Failures +// (e.g. no permission) silently leave the filter hidden. +const loadImPlatforms = async () => { + try { + const res: any = await listAllIMChannels(); + imPlatforms.value = configuredPlatforms(res?.data || []); + } catch { + imPlatforms.value = []; + } +}; + onMounted(async () => { const routeName = typeof route.name === 'string' ? route.name : (route.name ? String(route.name) : '') currentpath.value = routeName; @@ -712,6 +783,8 @@ onMounted(async () => { // 加载对话列表 getMessageList(); + // 检测当前租户是否配置了 IM 渠道,决定是否显示来源筛选 + loadImPlatforms(); // 若组织列表未加载则拉取一次,用于侧栏「待审批」角标 if (orgStore.organizations.length === 0) { orgStore.fetchOrganizations(); @@ -1448,6 +1521,43 @@ const onDragHandleMouseDown = (e: MouseEvent) => { position: relative; } +/* Right-aligned trailing controls on the「对话」title row (source-switch icon). */ +.menu-trailing { + margin-left: auto; + display: inline-flex; + align-items: center; + gap: 8px; + flex-shrink: 0; +} + +/* Source switcher icon: muted by default, brand-coloured when a non-web source is active. */ +.menu-source-icon { + font-size: 15px; + color: var(--td-text-color-placeholder); + opacity: 0.7; + flex-shrink: 0; + cursor: pointer; + transition: opacity 0.2s ease, color 0.2s ease; +} + +.menu_item:hover .menu-source-icon { + opacity: 1; +} + +.menu-source-icon-active { + color: var(--td-brand-color); + opacity: 1; +} + +/* Empty state when the active source has no sessions. */ +.submenu_empty { + padding: 24px 14px; + text-align: center; + font-size: 12px; + color: var(--td-text-color-placeholder); + user-select: none; +} + // 顶部 logo_row 右侧的图标按钮组(搜索 + 折叠),与折叠按钮风格一致 .logo_actions { display: flex; diff --git a/frontend/src/components/sessionSourceFilter.test.ts b/frontend/src/components/sessionSourceFilter.test.ts new file mode 100644 index 00000000..5a2c49a2 --- /dev/null +++ b/frontend/src/components/sessionSourceFilter.test.ts @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { + DEFAULT_SESSION_SOURCE, + buildSourceOptions, + configuredPlatforms, + shouldShowSourceFilter, +} from './sessionSourceFilter.ts' + +test('defaults the sidebar to web sessions so IM stays hidden until opted into', () => { + assert.equal(DEFAULT_SESSION_SOURCE, 'web') +}) + +test('source filter only appears once at least one IM channel is configured', () => { + assert.equal(shouldShowSourceFilter([]), false) + assert.equal(shouldShowSourceFilter(['feishu']), true) + assert.equal(shouldShowSourceFilter(['feishu', 'wecom']), true) +}) + +test('configuredPlatforms returns distinct platform keys in first-seen order', () => { + const channels = [ + { platform: 'feishu' }, + { platform: 'wecom' }, + { platform: 'feishu' }, // duplicate: a second feishu channel + { platform: '' }, // malformed row: ignored + ] + assert.deepEqual(configuredPlatforms(channels), ['feishu', 'wecom']) +}) + +test('configuredPlatforms tolerates an empty overview', () => { + assert.deepEqual(configuredPlatforms([]), []) +}) + +test('buildSourceOptions puts web first, then platforms with injected labels', () => { + const opts = buildSourceOptions(['feishu', 'wecom'], 'My chats', (p) => `LABEL:${p}`) + assert.deepEqual(opts, [ + { value: 'web', label: 'My chats', platform: null }, + { value: 'feishu', label: 'LABEL:feishu', platform: 'feishu' }, + { value: 'wecom', label: 'LABEL:wecom', platform: 'wecom' }, + ]) +}) + +test('buildSourceOptions with no IM platforms yields just the web option', () => { + assert.deepEqual(buildSourceOptions([], 'My chats', (p) => p), [ + { value: 'web', label: 'My chats', platform: null }, + ]) +}) diff --git a/frontend/src/components/sessionSourceFilter.ts b/frontend/src/components/sessionSourceFilter.ts new file mode 100644 index 00000000..ca1ad91c --- /dev/null +++ b/frontend/src/components/sessionSourceFilter.ts @@ -0,0 +1,57 @@ +// Pure logic for the sidebar's session source filter (issue #1560). +// +// IM-channel sessions are auto-generated operational traffic, not the user's own +// chats, and IM is an optional module. So the sidebar defaults to web sessions +// and only surfaces a quiet source filter for tenants that actually configured a +// channel — keeping IM low-key rather than promoting it to a first-class group. + +// 'web' = the user's own chats (no IM mapping); any other value is a platform +// key (e.g. 'feishu') selecting that channel's sessions. Sent verbatim as the +// `source` query param. The `(string & {})` arm keeps 'web' as an autocomplete +// hint instead of letting the union collapse to a bare `string`. +export type SessionSource = 'web' | (string & {}) + +export const DEFAULT_SESSION_SOURCE: SessionSource = 'web' + +// The source filter control is only rendered once the tenant has at least one +// configured IM channel — tenants that never enabled IM see an unchanged, +// channel-free sidebar. +export function shouldShowSourceFilter(configured: string[]): boolean { + return configured.length > 0 +} + +// Distinct platform keys from the tenant's IM channel overview, in first-seen +// order. Duplicates (multiple channels on one platform) collapse to one option, +// and malformed rows with no platform are dropped. +export function configuredPlatforms(channels: Array<{ platform: string }>): string[] { + const seen = new Set() + const out: string[] = [] + for (const c of channels) { + if (!c.platform || seen.has(c.platform)) continue + seen.add(c.platform) + out.push(c.platform) + } + return out +} + +export interface SourceOption { + value: SessionSource + label: string + // null for the user's own web chats; the platform key for an IM source. + platform: string | null +} + +// Build the source switcher's options: the user's own web chats first, then each +// configured IM platform in first-seen order. Labels are injected so this stays +// pure and unit-testable (no i18n dependency); logos are resolved by the caller +// (where the platform→asset map lives), keeping the dropdown component dumb. +export function buildSourceOptions( + platforms: string[], + webLabel: string, + labelForPlatform: (platform: string) => string, +): SourceOption[] { + return [ + { value: DEFAULT_SESSION_SOURCE, label: webLabel, platform: null }, + ...platforms.map((p) => ({ value: p, label: labelForPlatform(p), platform: p })), + ] +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 6cd7a048..8e274b92 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -27,6 +27,8 @@ export default { collapseSidebar: 'Collapse Sidebar', expandSidebar: 'Expand Sidebar', logoutSuccess: 'Logged out successfully', + myChats: 'My chats', + noSessions: 'No conversations yet', }, newUserGuide: { stepOf: '{current} / {total}', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index a91b6698..f214a746 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -27,6 +27,8 @@ export default { collapseSidebar: "사이드바 접기", expandSidebar: "사이드바 펼치기", logoutSuccess: "로그아웃되었습니다", + myChats: "내 대화", + noSessions: "대화가 없습니다", }, newUserGuide: { stepOf: "{current} / {total}", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index d65d3e3d..e07ac8de 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -25,6 +25,8 @@ export default { collapseSidebar: 'Свернуть боковую панель', expandSidebar: 'Развернуть боковую панель', logoutSuccess: 'Вы вышли из системы', + myChats: 'Мои чаты', + noSessions: 'Пока нет диалогов', agents: 'Агенты', organizations: 'Общие пространства' }, diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 0c66f29b..47268a5c 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -27,6 +27,8 @@ export default { collapseSidebar: "收起侧边栏", expandSidebar: "展开侧边栏", logoutSuccess: "已退出登录", + myChats: "我的对话", + noSessions: "暂无对话", }, newUserGuide: { stepOf: "{current} / {total}",