feat(frontend): add session source filter to sidebar (#1560)

IM-channel sessions were mixed in with the user's own chats. The sidebar
now defaults to web sessions; tenants with a configured IM channel get a
source switcher in the "对话" header to reach a specific platform.

- getSessionsList: optional `source` query param
- getMessageList: token-guarded loads (racing source switches / route
  changes can't append stale rows) + per-source pagination reset
- SourceSwitcherDropdown: scope dropdown mirroring KBSwitcherDropdown,
  scales to many platforms, reuses platform logos, closes on select
- empty state when a source has no sessions
- pure logic in sessionSourceFilter.ts with unit tests; zh/en/ko/ru i18n
This commit is contained in:
nullkey
2026-06-10 16:42:31 +08:00
committed by lyingbug
parent 232280d959
commit ac84dacc00
9 changed files with 398 additions and 8 deletions
+6 -2
View File
@@ -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) {
@@ -0,0 +1,163 @@
<template>
<t-popup
v-model:visible="visible"
trigger="click"
placement="bottom-left"
:overlay-style="{ padding: 0 }"
:overlay-inner-style="{ padding: 0 }"
>
<template #content>
<div class="source-switcher-card">
<div class="source-switcher-list">
<button
v-for="item in sortedList"
:key="item.value"
type="button"
class="source-switcher-row"
:class="{ active: item.value === current }"
@click="handleSelect(item.value)"
>
<img
v-if="item.logo"
:src="item.logo"
:alt="item.label"
class="source-switcher-row-logo"
/>
<t-icon
v-else
name="user"
class="source-switcher-row-icon"
size="16px"
/>
<span class="source-switcher-row-name" :title="item.label">{{ item.label }}</span>
<t-icon
v-if="item.value === current"
name="check"
class="source-switcher-row-check"
size="14px"
/>
</button>
</div>
</div>
</template>
<slot />
</t-popup>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue'
// A dumb scope switcher mirroring KBSwitcherDropdown's visual grammar. Logos are
// pre-resolved by the caller; web (no logo) falls back to a generic icon.
interface SourceItem {
value: string
label: string
logo?: string
}
const props = defineProps<{
sources: SourceItem[]
current: string
}>()
const emit = defineEmits<{
(e: 'select', value: string): void
}>()
// t-popup only closes on outside click; selecting an item must close it
// explicitly, otherwise the panel lingers and overlays the list below
// (switching source reloads in place, so nothing else dismisses it).
const visible = ref(false)
// Pin the current source to the top so users always see "where they are" without
// scrolling — same as KBSwitcherDropdown. The rest keeps the caller's order
// (web first, then configured platforms).
const sortedList = computed<SourceItem[]>(() => {
const all = props.sources || []
const current = all.find((s) => s.value === props.current)
if (!current) return all
return [current, ...all.filter((s) => s.value !== props.current)]
})
const handleSelect = (value: string): void => {
visible.value = false
if (value === props.current) return
emit('select', value)
}
</script>
<style scoped lang="less">
/* Mirrors KBSwitcherDropdown so both scope switchers stay visually identical. */
.source-switcher-card {
min-width: 200px;
max-width: 300px;
max-height: min(60vh, 420px);
display: flex;
flex-direction: column;
padding: 6px;
overflow: hidden;
}
.source-switcher-list {
flex: 1 1 auto;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 1px;
}
.source-switcher-row {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 10px;
border: none;
border-radius: 6px;
background: transparent;
color: var(--td-text-color-primary);
font-size: 13px;
line-height: 1.4;
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease;
text-align: left;
&:hover {
background: var(--td-bg-color-secondarycontainer);
}
&.active {
background: var(--td-brand-color-light, rgba(0, 82, 217, 0.08));
color: var(--td-brand-color);
font-weight: 500;
}
}
.source-switcher-row-logo {
flex: 0 0 auto;
width: 16px;
height: 16px;
border-radius: 3px;
object-fit: contain;
}
.source-switcher-row-icon {
flex: 0 0 auto;
color: var(--td-text-color-placeholder);
.source-switcher-row.active & {
color: var(--td-brand-color);
}
}
.source-switcher-row-name {
flex: 1 1 auto;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.source-switcher-row-check {
flex: 0 0 auto;
color: var(--td-brand-color);
}
</style>
+116 -6
View File
@@ -94,6 +94,14 @@
class="menu-pending-badge"
:title="t('organization.settings.pendingJoinRequestsBadge')">{{
orgStore.totalPendingJoinRequestCount }}</span>
<!-- 「对话」标题行右侧:会话来源切换图标 -->
<span v-if="item.path === 'creatChat'" class="menu-trailing">
<SourceSwitcherDropdown v-if="showSourceFilter && !batchMode"
:sources="sourceOptions" :current="currentSource" @select="switchSource">
<t-icon name="filter" @click.stop :title="currentSourceLabel"
:class="['menu-source-icon', { 'menu-source-icon-active': currentSource !== DEFAULT_SESSION_SOURCE }]" />
</SourceSwitcherDropdown>
</span>
</template>
</div>
</div>
@@ -138,6 +146,10 @@
</div>
</div>
</template>
<!-- 空状态:加载完成且当前来源无会话(切到无会话来源时不再白屏) -->
<div v-if="!loading && groupedSessions.length === 0" class="submenu_empty">
{{ t('menu.noSessions') }}
</div>
</div>
<!-- 批量管理底部操作条 -->
@@ -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<HTMLElement | null>(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<SessionSource>(DEFAULT_SESSION_SOURCE);
const imPlatforms = ref<string[]>([]);
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;
@@ -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 },
])
})
@@ -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<string>()
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 })),
]
}
+2
View File
@@ -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}',
+2
View File
@@ -27,6 +27,8 @@ export default {
collapseSidebar: "사이드바 접기",
expandSidebar: "사이드바 펼치기",
logoutSuccess: "로그아웃되었습니다",
myChats: "내 대화",
noSessions: "대화가 없습니다",
},
newUserGuide: {
stepOf: "{current} / {total}",
+2
View File
@@ -25,6 +25,8 @@ export default {
collapseSidebar: 'Свернуть боковую панель',
expandSidebar: 'Развернуть боковую панель',
logoutSuccess: 'Вы вышли из системы',
myChats: 'Мои чаты',
noSessions: 'Пока нет диалогов',
agents: 'Агенты',
organizations: 'Общие пространства'
},
+2
View File
@@ -27,6 +27,8 @@ export default {
collapseSidebar: "收起侧边栏",
expandSidebar: "展开侧边栏",
logoutSuccess: "已退出登录",
myChats: "我的对话",
noSessions: "暂无对话",
},
newUserGuide: {
stepOf: "{current} / {total}",