Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(embed): session sidebar grouping and embed theme alignment (#1657)

wizardchen20b01a6cd54f
diff --git a/frontend/src/components/SessionGroupByDropdown.vue b/frontend/src/components/SessionGroupByDropdown.vue
new file mode 100644
index 000000000..79ccbe05d
--- /dev/null
+++ b/frontend/src/components/SessionGroupByDropdown.vue
@@ -0,0 +1,123 @@
+<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="session-group-card">
+ <div class="session-group-header">{{ headerLabel }}</div>
+ <div class="session-group-list">
+ <button
+ v-for="item in modes"
+ :key="item.value"
+ type="button"
+ class="session-group-row"
+ :class="{ active: item.value === current }"
+ @click="handleSelect(item.value)"
+ >
+ <span class="session-group-row-name">{{ item.label }}</span>
+ <t-icon
+ v-if="item.value === current"
+ name="check"
+ class="session-group-row-check"
+ size="14px"
+ />
+ </button>
+ </div>
+ </div>
+ </template>
+ <slot />
+ </t-popup>
+</template>
+
+<script setup lang="ts">
+import { ref } from 'vue'
+import type { SessionGroupMode } from './sessionGrouping'
+
+interface GroupModeItem {
+ value: SessionGroupMode
+ label: string
+}
+
+defineProps<{
+ modes: GroupModeItem[]
+ current: SessionGroupMode
+ headerLabel: string
+}>()
+
+const emit = defineEmits<{
+ (e: 'select', value: SessionGroupMode): void
+}>()
+
+const visible = ref(false)
+
+const handleSelect = (value: SessionGroupMode): void => {
+ visible.value = false
+ emit('select', value)
+}
+</script>
+
+<style scoped lang="less">
+.session-group-card {
+ min-width: 180px;
+ max-width: 240px;
+ display: flex;
+ flex-direction: column;
+ padding: 0;
+ overflow: hidden;
+}
+
+.session-group-header {
+ padding: 8px 12px 6px;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--td-text-color-placeholder);
+ border-bottom: 1px solid var(--td-component-border);
+ user-select: none;
+}
+
+.session-group-list {
+ padding: 6px;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+}
+
+.session-group-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;
+ width: 100%;
+
+ &:hover {
+ background: var(--td-bg-color-secondarycontainer);
+ }
+
+ &.active {
+ color: var(--td-brand-color);
+ font-weight: 500;
+ }
+}
+
+.session-group-row-name {
+ flex: 1 1 auto;
+}
+
+.session-group-row-check {
+ flex: 0 0 auto;
+ color: var(--td-brand-color);
+}
+</style>
diff --git a/frontend/src/components/SessionSidebarRow.vue b/frontend/src/components/SessionSidebarRow.vue
new file mode 100644
index 000000000..bb4f65809
--- /dev/null
+++ b/frontend/src/components/SessionSidebarRow.vue
@@ -0,0 +1,56 @@
+<template>
+ <div
+ :class="[
+ 'submenu_item',
+ !batchMode && activePath === item.path ? 'submenu_item_active' : '',
+ batchMode && selectedIds.includes(item.id) ? 'submenu_item_selected' : '',
+ batchMode ? 'submenu_item_batch' : '',
+ ]"
+ @mouseenter="emit('hover-in')"
+ @mouseleave="emit('hover-out')"
+ @click="batchMode ? emit('toggle-select') : emit('navigate')"
+ >
+ <t-checkbox
+ v-if="batchMode"
+ class="batch-checkbox"
+ :checked="selectedIds.includes(item.id)"
+ @click.stop
+ @change="emit('toggle-select')"
+ />
+ <span class="submenu_title" :class="batchMode ? 'submenu_title--batch' : ''" :title="item.title">
+ <t-icon v-if="item.is_pinned" name="pin" class="submenu_pin_icon" />
+ <span class="submenu_title-text">{{ item.title }}</span>
+ </span>
+ <t-dropdown
+ v-if="!batchMode"
+ :options="menuOptions"
+ placement="bottom-right"
+ trigger="click"
+ @click="emit('menu-click', $event)"
+ >
+ <div @click.stop class="menu-more-wrap">
+ <t-icon name="ellipsis" class="menu-more" />
+ </div>
+ </t-dropdown>
+ </div>
+</template>
+
+<script setup lang="ts">
+defineProps<{
+ item: { id: string; path: string; title: string; is_pinned?: boolean }
+ batchMode: boolean
+ activePath: string
+ selectedIds: string[]
+ menuOptions: any[]
+ /** 渠道文件夹下的会话(样式与聊天区会话共用文案列对齐) */
+ nested?: boolean
+}>()
+
+const emit = defineEmits<{
+ (e: 'navigate'): void
+ (e: 'toggle-select'): void
+ (e: 'menu-click', data: { value: string }): void
+ (e: 'hover-in'): void
+ (e: 'hover-out'): void
+}>()
+</script>
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index 68d6613ff..dda6644fe 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -94,61 +94,123 @@
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>
</t-tooltip>
</div>
- <!-- 历史会话列表:与上方导航项一起滚动 -->
+ <!-- 历史会话:OpenAI 式「渠道文件夹 + 聊天列表」,各来源独立分页 -->
<div class="submenu" v-if="!uiStore.sidebarCollapsed">
- <!-- 骨架屏占位 -->
- <template v-if="loading && groupedSessions.length === 0">
- <div v-for="n in 5" :key="'skel-' + n" class="submenu_item_p">
- <div class="submenu_item">
- <t-skeleton animation="gradient" style="margin-left:14px;width:80%"
+ <template v-if="sessionListBooting && !hasAnySession">
+ <div v-for="n in 4" :key="'skel-' + n" class="submenu_item_p session-chat-row">
+ <div class="session-list-row session-list-row--flat">
+ <t-skeleton animation="gradient" class="session-list-row__body"
:row-col="[{ width: '100%', height: '14px' }]" />
</div>
</div>
</template>
- <template v-for="(group, groupIndex) in groupedSessions" :key="groupIndex">
- <div class="timeline_header">{{ group.label }}</div>
- <div class="submenu_item_p" v-for="(subitem, subindex) in group.items" :key="subitem.id">
- <div :class="['submenu_item', !batchMode && currentSecondpath == subitem.path ? 'submenu_item_active' : '', batchMode && batchSelectedIds.includes(subitem.id) ? 'submenu_item_selected' : '', batchMode ? 'submenu_item_batch' : '']"
- @mouseenter="mouseenteBotDownr(subitem.id)" @mouseleave="mouseleaveBotDown"
- @click="batchMode ? toggleBatchSelect(subitem.id) : gotopage(subitem.path)">
- <t-checkbox v-if="batchMode" class="batch-checkbox"
- :checked="batchSelectedIds.includes(subitem.id)" @click.stop
- @change="toggleBatchSelect(subitem.id)" />
- <span class="submenu_title" :style="batchMode ? 'margin-left:4px;' : 'margin-left:14px;'">
- <t-icon v-if="subitem.is_pinned" name="pin" class="submenu_pin_icon"
- :title="t('menu.pinned')" />
- <img v-if="subitem.im_platform && platformLogo(subitem.im_platform)"
- :src="platformLogo(subitem.im_platform)" :alt="subitem.im_platform"
- :title="subitem.im_platform" class="submenu_source_icon" />
- {{ subitem.title }}
+
+ <!-- 其他来源(IM / 网页嵌入):置顶一行入口,默认收起 -->
+ <div v-if="visibleChannelBuckets.length" class="session-channels-section">
+ <div class="timeline_header timeline_header--collapsible session-list-row session-list-row--flat"
+ role="button" tabindex="0"
+ @click="toggleChannelsSection"
+ @keydown.enter.prevent="toggleChannelsSection"
+ @keydown.space.prevent="toggleChannelsSection">
+ <span class="session-list-row__body">
+ <span class="session-header-text">
+ <span class="timeline_header-label">{{ t('menu.otherSources') }}</span>
+ <t-icon class="timeline_header-chevron"
+ :name="channelsSectionCollapsed ? 'chevron-right' : 'chevron-down'"
+ size="10px" />
+ </span>
+ </span>
+ </div>
+ <template v-if="!channelsSectionCollapsed">
+ <template v-for="bucket in visibleChannelBuckets" :key="bucket.key">
+ <div class="session-folder-header session-list-row session-list-row--flat"
+ role="button" tabindex="0"
+ @click="toggleSessionGroup(bucket.key)"
+ @keydown.enter.prevent="toggleSessionGroup(bucket.key)"
+ @keydown.space.prevent="toggleSessionGroup(bucket.key)">
+ <span class="session-list-row__body">
+ <span class="session-header-text">
+ <span class="session-folder-entry">
+ <img v-if="bucket.platform && platformLogo(bucket.platform)"
+ :src="platformLogo(bucket.platform)" :alt="bucket.platform"
+ class="session-channel-inline-icon" />
+ <t-icon v-else name="internet" class="session-channel-inline-icon"
+ size="12px" />
+ <span class="session-folder-label">{{ bucket.label }}</span>
+ </span>
+ <t-icon class="session-group-chevron"
+ :name="isSessionGroupCollapsed(bucket.key) ? 'chevron-right' : 'chevron-down'"
+ size="12px" />
+ </span>
+ </span>
+ </div>
+ <template v-if="!isSessionGroupCollapsed(bucket.key)">
+ <div v-if="bucket.loading && bucket.items.length === 0"
+ class="session-folder-loading">
+ <div class="session-list-row session-list-row--flat">
+ <span class="session-list-row__body">
+ <t-loading size="small" />
+ </span>
+ </div>
+ </div>
+ <div v-for="subitem in bucket.items" :key="subitem.id"
+ class="submenu_item_p session-chat-row session-folder-item">
+ <div class="session-list-row session-list-row--flat">
+ <div class="session-list-row__body">
+ <SessionSidebarRow :item="subitem" :batch-mode="batchMode"
+ :active-path="currentSecondpath" :selected-ids="batchSelectedIds"
+ :menu-options="buildSessionMenuOptions(subitem)"
+ @navigate="gotopage(subitem.path)"
+ @toggle-select="toggleBatchSelect(subitem.id)"
+ @menu-click="handleSessionMenuClick($event, subitem)"
+ @hover-in="mouseenteBotDownr(subitem.id)"
+ @hover-out="mouseleaveBotDown" />
+ </div>
+ </div>
+ </div>
+ </template>
+ </template>
+ </template>
+ </div>
+
+ <!-- 网页对话:按日期分组,直接展示 -->
+ <div class="session-web-list">
+ <template v-if="webBucket?.loaded && chatGroupedSessions.length === 0">
+ <div class="submenu_empty">{{ t('menu.noSessions') }}</div>
+ </template>
+ <template v-else>
+ <template v-for="group in chatGroupedSessions" :key="group.key">
+ <div v-if="group.label" class="timeline_header session-list-row session-list-row--flat">
+ <span class="session-list-row__body">
+ <span class="timeline_header-label">{{ group.label }}</span>
</span>
- <t-dropdown v-if="!batchMode" :options="buildSessionMenuOptions(subitem)"
- @click="handleSessionMenuClick($event, subitem.originalIndex, subitem)"
- placement="bottom-right" trigger="click">
- <div @click.stop class="menu-more-wrap">
- <t-icon name="ellipsis" class="menu-more" />
+ </div>
+ <div v-for="subitem in group.items" :key="subitem.id" class="submenu_item_p session-chat-row">
+ <div class="session-list-row session-list-row--flat">
+ <div class="session-list-row__body">
+ <SessionSidebarRow :item="subitem" :batch-mode="batchMode"
+ :active-path="currentSecondpath" :selected-ids="batchSelectedIds"
+ :menu-options="buildSessionMenuOptions(subitem)"
+ @navigate="gotopage(subitem.path)" @toggle-select="toggleBatchSelect(subitem.id)"
+ @menu-click="handleSessionMenuClick($event, subitem)"
+ @hover-in="mouseenteBotDownr(subitem.id)" @hover-out="mouseleaveBotDown" />
</div>
- </t-dropdown>
+ </div>
</div>
+ </template>
+ <div v-if="webBucket?.loading && chatGroupedSessions.length > 0"
+ class="session-list-loading session-list-row session-list-row--flat">
+ <span class="session-list-row__body">
+ <t-loading size="small" />
+ </span>
</div>
</template>
- <!-- 空状态:加载完成且当前来源无会话(切到无会话来源时不再白屏) -->
- <div v-if="!loading && groupedSessions.length === 0" class="submenu_empty">
- {{ t('menu.noSessions') }}
</div>
</div>
@@ -183,19 +245,35 @@
<script setup lang="ts">
import { storeToRefs } from 'pinia';
-import { onMounted, watch, computed, ref, h } from 'vue';
+import { onMounted, onUnmounted, watch, computed, ref, h, nextTick } 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 SessionSidebarRow from './SessionSidebarRow.vue';
import {
- DEFAULT_SESSION_SOURCE,
- buildSourceOptions,
+ SIDEBAR_BUCKET_PAGE_SIZE,
+ applyBucketCountProbe,
+ buildBucketDefinitions,
+ bucketHasMore,
+ bucketVisible,
+ createEmptyBucket,
+ flattenBucketItems,
+ isChannelBucket,
+ isChannelBucketKey,
+ mergeBucketPage,
+ prependSessionToWebBucket,
+ removeSessionFromBuckets,
+ type SidebarSessionBucket,
+} from './sessionSidebarBuckets';
+import type { SessionForGrouping } from './sessionGrouping';
+import { listAllEmbedChannels } from '@/api/embed/index';
+import {
+ classifyDateBucket,
configuredPlatforms,
- shouldShowSourceFilter,
- type SessionSource,
-} from './sessionSourceFilter';
+ groupSessionsByDate,
+ type DateBucketKey,
+} from './sessionGrouping';
import { logout as logoutApi } from '@/api/auth';
import { useMenuStore } from '@/stores/menu';
import { useAuthStore } from '@/stores/auth';
@@ -246,31 +324,58 @@ const cmdModKeyLabel = isMacLike ? '⌘' : 'Ctrl';
const route = useRoute();
const router = useRouter();
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 sessionBuckets = ref<Record<string, SidebarSessionBucket>>({});
+const bucketOrder = ref<string[]>([]);
+let bucketRequestToken = 0;
+const sessionListBooting = ref(false);
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) : '' }))
+const embedChannelNames = ref<Record<string, string>>({});
+// 分组折叠:其他来源整块 + 各来源文件夹默认收起;日期标题仅作分隔,不折叠。
+const channelsSectionCollapsed = ref(true);
+const collapsedSessionGroups = ref<Set<string>>(new Set());
+const channelBucketKeys = (keys: string[] = bucketOrder.value) =>
+ keys.filter((key) => isChannelBucketKey(key));
+const applyDefaultChannelCollapse = () => {
+ collapsedSessionGroups.value = new Set(channelBucketKeys());
+};
+const isSessionGroupCollapsed = (key: string) => collapsedSessionGroups.value.has(key);
+const toggleChannelsSection = async () => {
+ channelsSectionCollapsed.value = !channelsSectionCollapsed.value;
+ await refreshSessionListScrollability();
+};
+const ensureChannelBucketLoaded = async (key: string) => {
+ if (!isChannelBucketKey(key)) return;
+ const bucket = sessionBuckets.value[key];
+ if (!bucket || bucket.loaded || bucket.loading) return;
+ await loadBucketPage(key, 1);
+};
+
+const toggleSessionGroup = async (key: string) => {
+ const wasCollapsed = collapsedSessionGroups.value.has(key);
+ const next = new Set(collapsedSessionGroups.value);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ collapsedSessionGroups.value = next;
+ const expanded = wasCollapsed && !next.has(key);
+ if (expanded && isChannelBucketKey(key)) {
+ await ensureChannelBucketLoaded(key);
+ await ensureBucketFillsViewport(key);
+ }
+ await refreshSessionListScrollability();
+};
+const sessionListCanScroll = ref(false);
+const webBucket = computed(() => sessionBuckets.value.web);
+const visibleChannelBuckets = computed(() =>
+ bucketOrder.value
+ .map((key) => sessionBuckets.value[key])
+ .filter((bucket): bucket is SidebarSessionBucket => !!bucket && isChannelBucket(bucket) && bucketVisible(bucket)),
);
-// 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 hasAnySession = computed(() =>
+ Object.values(sessionBuckets.value).some((bucket) => bucket.items.length > 0),
);
-// 计算总页数
-const totalPages = computed(() => Math.ceil(total.value / page_size.value));
-const hasMore = computed(() => currentPage.value < totalPages.value);
type MenuItem = { title: string; icon: string; path: string; childrenPath?: string; children?: any[] };
const { menuArr, visibleMenuArr } = storeToRefs(usemenuStore);
let activeSubmenu = ref<string>('');
@@ -389,74 +494,53 @@ const currentKbInfo = ref<any>(null)
// 进行中的置顶/取消置顶请求,避免重复点击
const pinningIds = ref<Set<string>>(new Set())
-// 时间分组函数
-const getTimeCategory = (dateStr: string): string => {
- if (!dateStr) return t('time.earlier');
-
- const date = new Date(dateStr);
- const now = new Date();
- const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
- const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
- const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);
- const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000);
- const oneYearAgo = new Date(today.getTime() - 365 * 24 * 60 * 60 * 1000);
-
- const sessionDate = new Date(date.getFullYear(), date.getMonth(), date.getDate());
-
- if (sessionDate.getTime() >= today.getTime()) {
- return t('time.today');
- } else if (sessionDate.getTime() >= yesterday.getTime()) {
- return t('time.yesterday');
- } else if (date.getTime() >= sevenDaysAgo.getTime()) {
- return t('time.last7Days');
- } else if (date.getTime() >= thirtyDaysAgo.getTime()) {
- return t('time.last30Days');
- } else if (date.getTime() >= oneYearAgo.getTime()) {
- return t('time.lastYear');
- } else {
- return t('time.earlier');
- }
+const dateBucketLabels = computed<Record<DateBucketKey, string>>(() => ({
+ pinned: t('time.pinned'),
+ today: t('time.today'),
+ yesterday: t('time.yesterday'),
+ last7Days: t('time.last7Days'),
+ last30Days: t('time.last30Days'),
+ lastYear: t('time.lastYear'),
+ earlier: t('time.earlier'),
+}));
+
+// 「聊天」区内按日期分组(仅 web 会话)
+const chatGroupedSessions = computed(() => {
+ const web = sessionBuckets.value.web;
+ if (!web?.items.length) return [];
+
+ return groupSessionsByDate(
+ web.items,
+ dateBucketLabels.value,
+ (session) => classifyDateBucket(session.updated_at || session.created_at),
+ );
+});
+
+const refreshSessionListScrollability = async () => {
+ await nextTick();
+ const container = scrollContainer.value;
+ sessionListCanScroll.value = !!container && container.scrollHeight > container.clientHeight + 1;
};
-// 按时间分组Session列表,置顶会话单独置于最上方
-const groupedSessions = computed(() => {
- const chatMenu = (menuArr.value as unknown as MenuItem[]).find((item: MenuItem) => item.path === 'creatChat');
- if (!chatMenu || !chatMenu.children || chatMenu.children.length === 0) {
- return [];
- }
-
- const pinnedLabel = t('time.pinned');
- const groups: { [key: string]: any[] } = {
- [pinnedLabel]: [],
- [t('time.today')]: [],
- [t('time.yesterday')]: [],
- [t('time.last7Days')]: [],
- [t('time.last30Days')]: [],
- [t('time.lastYear')]: [],
- [t('time.earlier')]: []
- };
+/** 列表未撑满滚动区时自动续页(按当前可见 DOM 测量,避免折叠导致误判) */
+const ensureBucketFillsViewport = async (key: string) => {
+ const MAX_ITERATIONS = 20;
+ for (let i = 0; i < MAX_ITERATIONS; i++) {
+ await nextTick();
+ await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
+ const container = scrollContainer.value;
+ const bucket = sessionBuckets.value[key];
+ if (!container || !bucket || !bucketHasMore(bucket) || bucket.loading) break;
- (chatMenu.children as any[]).forEach((session: any, index: number) => {
- const withIndex = { ...session, originalIndex: index };
- if (session.is_pinned) {
- groups[pinnedLabel].push(withIndex);
- return;
- }
- const category = getTimeCategory(session.updated_at || session.created_at);
- groups[category].push(withIndex);
- });
+ const hasOverflow = container.scrollHeight > container.clientHeight + 1;
+ if (hasOverflow) break;
- // 按顺序返回非空分组(置顶组在最上方)
- const orderedLabels = [pinnedLabel, t('time.today'), t('time.yesterday'), t('time.last7Days'), t('time.last30Days'), t('time.lastYear'), t('time.earlier')];
- return orderedLabels
- .filter(label => groups[label].length > 0)
- .map(label => ({
- label,
- items: groups[label]
- }));
-});
+ const prevCount = bucket.items.length;
+ await loadBucketPage(key);
+ if ((sessionBuckets.value[key]?.items.length ?? 0) <= prevCount) break;
+ }
+};
-const loading = ref(false)
const mouseenteBotDownr = (val: string) => {
activeSubmenu.value = val;
}
@@ -509,19 +593,17 @@ const handleInlineBatchDelete = () => {
res = await batchDelSessions([...batchSelectedIds.value])
}
if (res && res.success === true) {
- const chatMenuItem = (menuArr.value as any[]).find((m: any) => m.path === 'creatChat');
if (isDeleteAll) {
- if (chatMenuItem) chatMenuItem.children = [];
+ usemenuStore.clearMenuArr();
total.value = 0;
+ await getMessageList();
} else {
- const ids = [...batchSelectedIds.value]
- if (chatMenuItem && chatMenuItem.children) {
- for (const id of ids) {
- const idx = chatMenuItem.children.findIndex((s: any) => s.id === id);
- if (idx !== -1) chatMenuItem.children.splice(idx, 1);
- }
+ let next = sessionBuckets.value;
+ for (const id of batchSelectedIds.value) {
+ next = removeSessionFromBuckets(next, id);
}
- total.value = Math.max(0, total.value - ids.length);
+ sessionBuckets.value = next;
+ syncMenuStoreFromBuckets();
}
const currentChatId = route.params.chatid as string;
if (currentChatId && (isDeleteAll || batchSelectedIds.value.includes(currentChatId))) {
@@ -542,9 +624,9 @@ const handleInlineBatchDelete = () => {
})
}
-const handleSessionMenuClick = (data: { value: string }, index: number, item: any) => {
+const handleSessionMenuClick = (data: { value: string }, item: any) => {
if (data?.value === 'delete') {
- delCard(index, item);
+ delCard(item);
} else if (data?.value === 'clearMessages') {
clearMessages(item);
} else if (data?.value === 'batchManage') {
@@ -579,6 +661,21 @@ const buildSessionMenuOptions = (item: any) => {
return options;
};
+const updateSessionInBuckets = (
+ sessionId: string,
+ patch: Partial<{ is_pinned: boolean; pinned_at: string | null; title: string; isNoTitle?: boolean }>,
+) => {
+ const next: Record<string, SidebarSessionBucket> = {};
+ for (const [key, bucket] of Object.entries(sessionBuckets.value)) {
+ next[key] = {
+ ...bucket,
+ items: bucket.items.map((row) => (row.id === sessionId ? { ...row, ...patch } : row)),
+ };
+ }
+ sessionBuckets.value = next;
+ syncMenuStoreFromBuckets();
+};
+
const togglePin = (item: any, pin: boolean) => {
if (pinningIds.value.has(item.id)) return;
pinningIds.value.add(item.id);
@@ -586,21 +683,10 @@ const togglePin = (item: any, pin: boolean) => {
const call = pin ? pinSession(item.id) : unpinSession(item.id);
call.then((res: any) => {
if (res && res.success) {
- // 乐观更新本地列表项,避免整表重拉引起抖动。
- const chatMenu = (menuArr.value as any[]).find((m: any) => m.path === 'creatChat');
- const idx = chatMenu?.children?.findIndex((s: any) => s.id === item.id) ?? -1;
- if (idx >= 0) {
- const target = chatMenu.children[idx];
- target.is_pinned = pin;
- target.pinned_at = pin ? new Date().toISOString() : null;
- // 置顶时把元素挪到数组最前,确保在置顶分组中出现在最上方
- // (groupedSessions 按 children 顺序分组)。取消置顶时无需移动,
- // 元素会自然回到它在时间分组内的原位。
- if (pin && idx > 0) {
- chatMenu.children.splice(idx, 1);
- chatMenu.children.unshift(target);
- }
- }
+ updateSessionInBuckets(item.id, {
+ is_pinned: pin,
+ pinned_at: pin ? new Date().toISOString() : null,
+ });
} else {
MessagePlugin.error(pin ? t('menu.pinFailed') : t('menu.unpinFailed'));
}
@@ -626,30 +712,15 @@ const clearMessages = (item: any) => {
});
};
-const delCard = (index: number, item: any) => {
+const delCard = (item: any) => {
delSession(item.id).then((res: any) => {
if (res && (res as any).success) {
- // 找到 'creatChat' 菜单项
- const chatMenuItem = (menuArr.value as any[]).find((m: any) => m.path === 'creatChat');
-
- if (chatMenuItem && chatMenuItem.children) {
- const children = chatMenuItem.children;
- // 通过ID查找索引,比依赖传入的index更安全
- const actualIndex = children.findIndex((s: any) => s.id === item.id);
-
- if (actualIndex !== -1) {
- children.splice(actualIndex, 1);
- }
- }
+ sessionBuckets.value = removeSessionFromBuckets(sessionBuckets.value, item.id);
+ syncMenuStoreFromBuckets();
if (item.id == route.params.chatid) {
- // 删除当前会话后,跳转到全局创建聊天页面
router.push('/platform/creatChat');
}
- // 更新总数
- if (total.value > 0) {
- total.value--;
- }
} else {
MessagePlugin.error(t('chat.deleteSessionFailed'));
}
@@ -664,69 +735,182 @@ const debounce = (fn: (...args: any[]) => void, delay: number) => {
timer = setTimeout(() => fn(...args), delay)
}
}
-// 滚动处理
-const checkScrollBottom = () => {
- const container = scrollContainer.value
- if (!container) return
+const mapSessionRow = (item: any) => ({
+ title: item.title ? item.title : t('menu.newSession'),
+ path: `chat/${item.id}`,
+ id: item.id,
+ isMore: false,
+ isNoTitle: item.title ? false : true,
+ created_at: item.created_at,
+ updated_at: item.updated_at,
+ is_pinned: !!item.is_pinned,
+ pinned_at: item.pinned_at || null,
+ im_platform: item.im_platform || '',
+ description: item.description || '',
+});
+
+const syncMenuStoreFromBuckets = () => {
+ usemenuStore.clearMenuArr();
+ const flat = flattenBucketItems(sessionBuckets.value, bucketOrder.value);
+ flat.forEach((item) => usemenuStore.updatemenuArr(item));
+ total.value = flat.length;
+};
+
+const menuChildToSessionRow = (item: Record<string, unknown>): SessionForGrouping & { path: string } => {
+ const id = String(item.id);
+ return {
+ id,
+ path: typeof item.path === 'string' ? item.path : `chat/${id}`,
+ title: typeof item.title === 'string' ? item.title : undefined,
+ is_pinned: !!item.is_pinned,
+ created_at: typeof item.created_at === 'string' ? item.created_at : undefined,
+ updated_at: typeof item.updated_at === 'string' ? item.updated_at : undefined,
+ im_platform: typeof item.im_platform === 'string' ? item.im_platform : '',
+ description: typeof item.description === 'string' ? item.description : '',
+ };
+};
+
+const sessionExistsInBuckets = (sessionId: string) =>
+ Object.values(sessionBuckets.value).some((bucket) => bucket.items.some((row) => row.id === sessionId));
+
+/** 创建会话后 menuStore 已乐观写入,但列表实际渲染自 sessionBuckets,需补齐。 */
+const ensureSessionInSidebar = (sessionId: string) => {
+ if (!sessionId || sessionExistsInBuckets(sessionId)) return;
+
+ const web = sessionBuckets.value.web;
+ if (!web) return;
+
+ const chatMenu = (menuArr.value as unknown as MenuItem[]).find((item) => item.path === 'creatChat');
+ const fromStore = (chatMenu?.children as Record<string, unknown>[] | undefined)
+ ?.find((item) => item.id === sessionId);
+ if (!fromStore) return;
+
+ sessionBuckets.value = {
+ ...sessionBuckets.value,
+ web: prependSessionToWebBucket(web, menuChildToSessionRow(fromStore)),
+ };
+ total.value = flattenBucketItems(sessionBuckets.value, bucketOrder.value).length;
+};
+
+const rebuildBucketDefinitions = () => buildBucketDefinitions(
+ imPlatforms.value,
+ embedChannelNames.value,
+ {
+ web: t('menu.myChats'),
+ imPlatform: (platform) => t(`agentEditor.im.${platform}`),
+ embedChannel: (name) => name,
+ },
+);
+
+/** 首屏轻量探测各渠道是否有会话(page_size=1 只取 total),避免展示空文件夹 */
+const probeChannelBucketCounts = async (keys: string[], token: number) => {
+ const targets = keys.filter((key) => isChannelBucketKey(key));
+ await Promise.all(
+ targets.map(async (key) => {
+ const bucket = sessionBuckets.value[key];
+ if (!bucket) return;
+ try {
+ const res: any = await getSessionsList(1, 1, bucket.apiSource);
+ if (token !== bucketRequestToken) return;
+ sessionBuckets.value = {
+ ...sessionBuckets.value,
+ [key]: applyBucketCountProbe(bucket, res?.total ?? 0),
+ };
+ } catch {
+ if (token !== bucketRequestToken) return;
+ sessionBuckets.value = {
+ ...sessionBuckets.value,
+ [key]: applyBucketCountProbe(bucket, 0),
+ };
+ }
+ }),
+ );
+};
+
+const loadBucketPage = async (key: string, page?: number, token?: number) => {
+ const activeToken = token ?? bucketRequestToken;
+ const bucket = sessionBuckets.value[key];
+ if (!bucket || bucket.loading) return;
+
+ const nextPage = page ?? bucket.page + 1;
+ sessionBuckets.value = {
+ ...sessionBuckets.value,
+ [key]: { ...bucket, loading: true },
+ };
+
+ try {
+ const res: any = await getSessionsList(nextPage, SIDEBAR_BUCKET_PAGE_SIZE, bucket.apiSource);
+ if (activeToken !== bucketRequestToken) return;
+ const rows = (res?.data || []).map((item: any) => mapSessionRow(item));
+ const current = sessionBuckets.value[key];
+ sessionBuckets.value = {
+ ...sessionBuckets.value,
+ [key]: mergeBucketPage(current, rows, res?.total ?? rows.length, nextPage),
+ };
+ syncMenuStoreFromBuckets();
+ await refreshSessionListScrollability();
+ } catch {
+ if (activeToken !== bucketRequestToken) return;
+ const current = sessionBuckets.value[key];
+ sessionBuckets.value = {
+ ...sessionBuckets.value,
+ [key]: { ...current, loading: false, loaded: true },
+ };
+ }
+};
- const { scrollTop, scrollHeight, clientHeight } = container
- const isBottom = scrollHeight - (scrollTop + clientHeight) < 100 // 触底阈值
+const initSessionBuckets = async () => {
+ const token = ++bucketRequestToken;
+ sessionListBooting.value = true;
- if (isBottom && hasMore.value && !loading.value) {
- currentPage.value++;
- getMessageList(true);
+ const defs = rebuildBucketDefinitions();
+ bucketOrder.value = defs.map((def) => def.key);
+ const buckets: Record<string, SidebarSessionBucket> = {};
+ for (const def of defs) {
+ buckets[def.key] = createEmptyBucket(def);
}
-}
-const handleScroll = debounce(checkScrollBottom, 200)
-const getMessageList = async (isLoadMore = false) => {
- // 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) {
- currentPage.value = 1; // 重置页码
- usemenuStore.clearMenuArr();
- }
-
- // 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) {
- res.data.forEach((item: any) => {
- let obj = {
- title: item.title ? item.title : t('menu.newSession'),
- path: `chat/${item.id}`,
- id: item.id,
- isMore: false,
- isNoTitle: item.title ? false : true,
- created_at: item.created_at,
- updated_at: item.updated_at,
- is_pinned: !!item.is_pinned,
- pinned_at: item.pinned_at || null,
- im_platform: item.im_platform || '',
- }
- usemenuStore.updatemenuArr(obj)
- });
- }
- // 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;
- })
-}
+ sessionBuckets.value = buckets;
+
+ // 首屏:拉 web 会话 + 轻量探测各渠道 count(不拉完整列表);有会话的渠道才展示文件夹
+ const channelKeys = defs.map((def) => def.key).filter((key) => isChannelBucketKey(key));
+ await Promise.all([
+ loadBucketPage('web', 1, token),
+ probeChannelBucketCounts(channelKeys, token),
+ ]);
+
+ if (token === bucketRequestToken) {
+ sessionListBooting.value = false;
+ applyDefaultChannelCollapse();
+ syncMenuStoreFromBuckets();
+ await ensureBucketFillsViewport('web');
+ await refreshSessionListScrollability();
+ }
+};
+
+const getMessageList = async () => {
+ await initSessionBuckets();
+};
+
+// 滚动到底时仅为「聊天」区加载下一页 web 会话
+const checkScrollBottom = async () => {
+ const container = scrollContainer.value;
+ const web = sessionBuckets.value.web;
+ if (!container || !web || !bucketHasMore(web) || web.loading) return;
+
+ const { scrollTop, scrollHeight, clientHeight } = container;
+ const hasOverflow = scrollHeight > clientHeight + 1;
+ if (!hasOverflow) {
+ await ensureBucketFillsViewport('web');
+ return;
+ }
+
+ const isNearBottom = scrollHeight - (scrollTop + clientHeight) < 100;
+ if (!isNearBottom) return;
+
+ await loadBucketPage('web');
+};
+
+const handleScroll = debounce(checkScrollBottom, 200);
async function loadCurrentKbInfo(kbId: string) {
if (!kbId || !isInKnowledgeBase.value) {
@@ -743,25 +927,29 @@ 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 () => {
+const loadSessionOriginMeta = async () => {
try {
const res: any = await listAllIMChannels();
imPlatforms.value = configuredPlatforms(res?.data || []);
} catch {
imPlatforms.value = [];
}
+ try {
+ const res: any = await listAllEmbedChannels();
+ const names: Record<string, string> = {};
+ for (const ch of res?.data || []) {
+ if (ch?.id && ch?.name) names[ch.id] = ch.name;
+ }
+ embedChannelNames.value = names;
+ } catch {
+ embedChannelNames.value = {};
+ }
+};
+
+const handleSessionTitleUpdated = (event: Event) => {
+ const detail = (event as CustomEvent<{ sessionId?: string; title?: string }>).detail;
+ if (!detail?.sessionId || !detail.title) return;
+ updateSessionInBuckets(detail.sessionId, { title: detail.title, isNoTitle: false });
};
onMounted(async () => {
@@ -771,6 +959,8 @@ onMounted(async () => {
currentSecondpath.value = `chat/${route.params.chatid}`;
}
+ window.addEventListener('session-title-updated', handleSessionTitleUpdated);
+
isLiteEdition.value = authStore.isLiteMode
getSystemInfo().then(res => {
if (res.data?.edition === 'lite') {
@@ -781,16 +971,22 @@ onMounted(async () => {
await loadCurrentKbInfo((route.params as any)?.kbId as string)
- // 加载对话列表
- getMessageList();
- // 检测当前租户是否配置了 IM 渠道,决定是否显示来源筛选
- loadImPlatforms();
+ await loadSessionOriginMeta();
+ await getMessageList();
+ const initialChatId = route.params.chatid as string | undefined;
+ if (initialChatId) {
+ ensureSessionInSidebar(initialChatId);
+ }
// 若组织列表未加载则拉取一次,用于侧栏「待审批」角标
if (orgStore.organizations.length === 0) {
orgStore.fetchOrganizations();
}
});
+onUnmounted(() => {
+ window.removeEventListener('session-title-updated', handleSessionTitleUpdated);
+});
+
watch([() => route.name, () => route.params], (newvalue, oldvalue) => {
const nameStr = typeof newvalue[0] === 'string' ? (newvalue[0] as string) : (newvalue[0] ? String(newvalue[0]) : '')
currentpath.value = nameStr;
@@ -800,20 +996,11 @@ watch([() => route.name, () => route.params], (newvalue, oldvalue) => {
currentSecondpath.value = "";
}
- // 只在必要时刷新对话列表,避免不必要的重新加载导致列表抖动
- // 需要刷新的情况:
- // 1. 创建新会话后(从 creatChat/kbCreatChat 跳转到 chat/:id 且该 id 不在列表里)
- // 2. 删除会话后已在 delCard 中处理,不需要在这里刷新
- const oldRouteNameStr = typeof oldvalue?.[0] === 'string' ? (oldvalue[0] as string) : (oldvalue?.[0] ? String(oldvalue[0]) : '')
- const leavingCreatChat = (oldRouteNameStr === 'globalCreatChat' || oldRouteNameStr === 'kbCreatChat') &&
- nameStr !== 'globalCreatChat' && nameStr !== 'kbCreatChat';
- // 只有跳转到的目标会话不在当前列表里,才认为是"刚创建的新会话",
- // 避免从 creatChat 点击已有 session 时把整个列表清空重拉造成抖动。
+ // 创建新会话时 creatChat 会先 updataMenuChildren,再跳转 chat/:id。
+ // 侧栏实际渲染 sessionBuckets,需按 buckets 判断是否缺失,不能把 menuStore 当真相来源。
const newChatId = (newvalue[1] as any)?.chatid as string | undefined;
- const targetIsNewSession = !!newChatId && !allSessionIds.value.includes(newChatId);
-
- if (leavingCreatChat && targetIsNewSession) {
- getMessageList();
+ if (nameStr === 'chat' && newChatId) {
+ ensureSessionInSidebar(newChatId);
}
// 路由变化时更新图标状态和知识库信息(不涉及对话列表)
@@ -959,6 +1146,13 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
</script>
<style lang="less" scoped>
.aside_box {
+ // 侧栏水平栅格:图标列与文案列统一对齐(Logo / 菜单 / 会话分组 / 会话行)
+ --sidebar-inset-x: 14px;
+ --sidebar-icon-size: 18px;
+ --sidebar-channel-icon: 14px;
+ --sidebar-icon-gap: 8px;
+ --sidebar-text-inset: calc(var(--sidebar-inset-x) + var(--sidebar-icon-size) + var(--sidebar-icon-gap)); // 40px
+
min-width: 260px;
width: 260px;
padding: 8px 6px 6px;
@@ -990,7 +1184,7 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
.menu_item {
justify-content: center;
- padding: 10px 0;
+ padding: 9px 0;
.menu_item-box {
justify-content: center;
@@ -1016,9 +1210,9 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
display: flex;
align-items: center;
justify-content: space-between;
- height: 56px;
+ height: 50px;
flex-shrink: 0;
- padding: 0 8px 0 8px;
+ padding: 0 10px 0 var(--sidebar-inset-x);
}
.sidebar-toggle {
@@ -1062,7 +1256,7 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
overflow: hidden;
.logo {
- width: 134px;
+ width: 128px;
height: auto;
}
@@ -1203,8 +1397,8 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
}
.menu_p {
- height: 50px;
- padding: 4px 0;
+ height: 46px;
+ padding: 3px 0;
box-sizing: border-box;
}
@@ -1213,10 +1407,10 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
display: flex;
align-items: center;
justify-content: space-between;
- height: 42px;
- padding: 10px 8px 10px 14px;
+ height: 38px;
+ padding: 8px 10px 8px var(--sidebar-inset-x);
box-sizing: border-box;
- margin-bottom: 3px;
+ margin-bottom: 2px;
border-radius: 4px;
transition: background-color 0.2s ease;
@@ -1238,7 +1432,9 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
.menu_icon {
display: flex;
- margin-right: 8px;
+ flex: 0 0 var(--sidebar-icon-size);
+ width: var(--sidebar-icon-size);
+ margin-right: var(--sidebar-icon-gap);
color: var(--td-text-color-secondary);
.icon {
@@ -1266,14 +1462,16 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
font-family: var(--app-font-family);
font-size: 14px;
font-style: normal;
- margin-left: 4px;
+ min-width: 0;
+ padding-top: 3px;
}
- .submenu_pin_icon {
+ :deep(.submenu_pin_icon) {
color: inherit;
font-size: 12px;
margin-right: 4px;
vertical-align: middle;
+ flex-shrink: 0;
}
.submenu_source_icon {
@@ -1290,61 +1488,258 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
transition: filter 0.15s ease, opacity 0.15s ease;
}
- .submenu_item:hover .submenu_source_icon,
- .submenu_item_active .submenu_source_icon {
+ :deep(.submenu_item:hover .submenu_source_icon),
+ :deep(.submenu_item_active .submenu_source_icon) {
filter: none;
opacity: 1;
}
- @keyframes menuItemFadeIn {
- from {
- opacity: 0;
- transform: translateX(-4px);
+ .session-channels-section {
+ margin-bottom: 2px;
+
+ .session-folder-header {
+ font-size: 12px;
+ line-height: 20px;
+ }
+
+ // 与置顶会话一致:图标内联在标题前,间距 4px
+ .session-folder-entry {
+ display: inline-flex;
+ align-items: center;
+ min-width: 0;
+ flex: 1 1 auto;
+ overflow: hidden;
+ }
+
+ .session-channel-inline-icon {
+ flex-shrink: 0;
+ width: 12px;
+ height: 12px;
+ margin-right: 4px;
+ object-fit: contain;
+ filter: grayscale(1);
+ opacity: 0.55;
}
- to {
- opacity: 1;
- transform: translateX(0);
+ :deep(.session-channel-inline-icon.t-icon) {
+ color: var(--td-text-color-secondary);
+ opacity: 0.75;
}
}
+ // 标题 + 折叠箭头紧挨排列,箭头 hover 时才出现
+ // 列表行统一栅格:左缘 inset-x + 图标槽 18px + 间距 8px → 文案列与主菜单文字对齐
+ .session-list-row {
+ display: flex;
+ align-items: center;
+ gap: var(--sidebar-icon-gap);
+ padding: 0 10px 0 var(--sidebar-inset-x);
+ min-width: 0;
+ box-sizing: border-box;
+ }
+
+ .session-list-row__icon {
+ flex: 0 0 var(--sidebar-icon-size);
+ width: var(--sidebar-icon-size);
+ height: var(--sidebar-icon-size);
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ }
+
+ .session-list-row__body {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ }
+
+ // 聊天区分组标题 / 会话行:与「聊天」节标题同列左对齐,不再预留图标槽
+ .session-list-row--flat {
+ padding-left: var(--sidebar-inset-x);
+ gap: 0;
+ }
+
+ // 渠道文件夹内会话:与文件夹标题文字列对齐
+ .session-list-row--nested {
+ padding-left: var(--sidebar-text-inset);
+ gap: 0;
+ }
+
+ .session-header-text {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ min-width: 0;
+ }
+
+ .session-group-chevron {
+ flex: 0 0 auto;
+ color: var(--td-text-color-placeholder);
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ }
+
+ .session-folder-header {
+ padding-top: 2px;
+ padding-bottom: 2px;
+ border-radius: 6px;
+ cursor: pointer;
+ color: var(--td-text-color-primary);
+ font-size: 13px;
+ line-height: 20px;
+ user-select: none;
+ outline: none;
+
+ &:hover,
+ &:focus-visible {
+ background: var(--td-bg-color-container-hover);
+
+ .session-group-chevron {
+ opacity: 1;
+ }
+ }
+ }
+
+ .session-folder-icon {
+ width: var(--sidebar-channel-icon);
+ height: var(--sidebar-channel-icon);
+ object-fit: contain;
+ flex-shrink: 0;
+ }
+
+ .session-folder-label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .session-folder-loading {
+ display: flex;
+ align-items: center;
+ padding: 4px 0;
+ color: var(--td-text-color-placeholder);
+
+ .session-list-row {
+ width: 100%;
+ }
+ }
+
+ .session-list-loading {
+ display: flex;
+ align-items: center;
+ min-height: 26px;
+ color: var(--td-text-color-placeholder);
+ }
+
.timeline_header {
font-family: var(--app-font-family);
font-size: 11px;
font-weight: 600;
color: var(--td-text-color-disabled);
- padding: 6px 14px 3px 14px;
- margin-top: 4px;
- line-height: 17px;
+ padding-top: 4px;
+ padding-bottom: 1px;
+ margin-top: 0;
+ line-height: 16px;
user-select: none;
- animation: menuItemFadeIn 0.25s ease-out;
+ }
- &:first-child {
- margin-top: 2px;
+ .timeline_header-label {
+ white-space: nowrap;
+ }
+
+ .timeline_header--collapsible {
+ cursor: pointer;
+ outline: none;
+
+ &:hover,
+ &:focus-visible {
+ color: var(--td-text-color-secondary);
}
}
+ .timeline_header-chevron {
+ flex: 0 0 auto;
+ color: inherit;
+ opacity: 0.55;
+ transition: opacity 0.15s ease;
+ }
+
+ .timeline_header--collapsible:hover .timeline_header-chevron,
+ .timeline_header--collapsible:focus-visible .timeline_header-chevron {
+ opacity: 1;
+ }
+
.submenu_item_p {
- height: 34px;
- padding: 1px 0px 1px 0px;
+ padding: 0;
box-sizing: border-box;
- animation: menuItemFadeIn 0.25s ease-out;
- }
+ min-width: 0;
+ overflow: hidden;
+ &.session-chat-row .session-list-row {
+ min-height: 30px;
+ border-radius: 6px;
+ transition: background 0.15s ease, color 0.15s ease;
+ }
- .submenu_item {
+ &.session-chat-row:hover .session-list-row {
+ background: var(--td-bg-color-container-hover);
+
+ :deep(.menu-more) {
+ color: var(--td-text-color-primary);
+ }
+
+ :deep(.menu-more-wrap) {
+ opacity: 1;
+ }
+ }
+
+ &.session-chat-row:has(:deep(.submenu_item_active)) .session-list-row {
+ background: var(--td-brand-color-light);
+
+ :deep(.submenu_item) {
+ color: var(--td-brand-color);
+ }
+
+ :deep(.menu-more) {
+ color: var(--td-brand-color);
+ }
+
+ :deep(.menu-more-wrap) {
+ opacity: 1;
+ }
+ }
+
+ &.session-chat-row:has(:deep(.submenu_item_selected)) .session-list-row {
+ background: rgba(7, 192, 95, 0.05);
+ }
+ }
+
+ // SessionSidebarRow 为子组件,需 :deep 才能让标题省略号生效
+ :deep(.submenu_item) {
cursor: pointer;
display: flex;
align-items: center;
color: var(--td-text-color-primary);
font-weight: 400;
- line-height: 19px;
- height: 30px;
- padding-left: 0px;
- padding-right: 10px;
+ font-size: 14px;
+ line-height: 20px;
+ height: 100%;
+ width: 100%;
+ padding: 4px 0;
position: relative;
+ min-width: 0;
+ background: transparent;
.submenu_title {
+ display: flex;
+ align-items: center;
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ }
+
+ .submenu_title-text {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
@@ -1364,53 +1759,24 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
color: var(--td-brand-color);
}
- .sub_title {
- margin-left: 14px;
+ .submenu_title--batch {
+ margin-left: 4px;
}
- &:hover {
- background: var(--td-bg-color-container-hover);
- color: var(--td-text-color-primary);
- border-radius: 6px;
-
- .menu-more {
- color: var(--td-text-color-primary);
- }
-
- .menu-more-wrap {
- opacity: 1;
- }
- }
- }
-
- .submenu_item_active {
- background: var(--td-brand-color-light) !important;
- color: var(--td-brand-color) !important;
- border-radius: 6px;
-
- .menu-more {
- color: var(--td-brand-color) !important;
- }
-
- .menu-more-wrap {
- opacity: 1;
+ &.submenu_item_batch {
+ padding-left: 0;
}
}
- .submenu_item_batch {
- padding-left: 8px;
+ :deep(.submenu_item_batch) {
cursor: pointer;
user-select: none;
}
- .submenu_item_selected {
- background: rgba(7, 192, 95, 0.05) !important;
- border-radius: 6px;
- }
-
.batch-checkbox {
flex-shrink: 0;
}
+
}
.batch-inline-footer {
@@ -1521,35 +1887,7 @@ 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. */
+/* Empty state when there are no sessions. */
.submenu_empty {
padding: 24px 14px;
text-align: center;
diff --git a/frontend/src/components/sessionGrouping.test.ts b/frontend/src/components/sessionGrouping.test.ts
new file mode 100644
index 000000000..78d19fa39
--- /dev/null
+++ b/frontend/src/components/sessionGrouping.test.ts
@@ -0,0 +1,98 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ EMBED_SESSION_MARKER_PREFIX,
+ classifyDateBucket,
+ configuredPlatforms,
+ groupSessions,
+ groupSessionsBySource,
+ resolveSessionOrigin,
+ shouldShowSessionSourceBadge,
+} from './sessionGrouping.ts'
+
+const sourceLabels = {
+ web: 'Web',
+ embedFallback: 'Embed',
+ embedChannel: (id: string) => `Embed ${id}`,
+ imPlatform: (p: string) => `IM ${p}`,
+}
+
+test('resolveSessionOrigin distinguishes web, IM, and embed sessions', () => {
+ assert.deepEqual(resolveSessionOrigin({ id: '1' }), { kind: 'web' })
+ assert.deepEqual(resolveSessionOrigin({ id: '2', im_platform: 'feishu' }), {
+ kind: 'im',
+ platform: 'feishu',
+ })
+ assert.deepEqual(
+ resolveSessionOrigin({
+ id: '3',
+ description: `${EMBED_SESSION_MARKER_PREFIX}ch-1`,
+ }),
+ { kind: 'embed', channelId: 'ch-1' },
+ )
+})
+
+test('configuredPlatforms returns distinct platform keys in first-seen order', () => {
+ const channels = [
+ { platform: 'feishu' },
+ { platform: 'wecom' },
+ { platform: 'feishu' },
+ { platform: '' },
+ ]
+ assert.deepEqual(configuredPlatforms(channels), ['feishu', 'wecom'])
+})
+
+test('groupSessionsBySource orders web, configured IM, then embed channels', () => {
+ const sessions = [
+ { id: 'w', title: 'web chat' },
+ { id: 'f', title: 'feishu', im_platform: 'feishu' },
+ { id: 'e', title: 'embed', description: `${EMBED_SESSION_MARKER_PREFIX}ec-1` },
+ ]
+ const groups = groupSessionsBySource(sessions, sourceLabels, { 'ec-1': 'Help widget' }, ['feishu'], 'Pinned')
+ assert.deepEqual(
+ groups.map((g) => g.key),
+ ['web', 'im:feishu', 'embed:ec-1'],
+ )
+ assert.equal(groups[2]?.label, 'Help widget')
+})
+
+test('groupSessions date mode keeps pinned sessions in their own bucket', () => {
+ const now = new Date().toISOString()
+ const groups = groupSessions(
+ 'date',
+ [
+ { id: 'p', is_pinned: true, updated_at: now },
+ { id: 't', updated_at: now },
+ ],
+ {
+ pinnedLabel: 'Pinned',
+ bucketLabels: {
+ pinned: 'Pinned',
+ today: 'Today',
+ yesterday: 'Yesterday',
+ last7Days: '7d',
+ last30Days: '30d',
+ lastYear: 'Year',
+ earlier: 'Earlier',
+ },
+ categorizeDate: () => 'today',
+ sourceLabels,
+ embedChannelNames: {},
+ configuredImPlatforms: [],
+ },
+ )
+ assert.deepEqual(
+ groups.map((g) => g.key),
+ ['pinned', 'today'],
+ )
+})
+
+test('classifyDateBucket buckets recent sessions as today', () => {
+ assert.equal(classifyDateBucket(new Date().toISOString()), 'today')
+})
+
+test('shouldShowSessionSourceBadge is off when channels use separate folders', () => {
+ assert.equal(shouldShowSessionSourceBadge('date'), false)
+ assert.equal(shouldShowSessionSourceBadge('none'), false)
+})
diff --git a/frontend/src/components/sessionGrouping.ts b/frontend/src/components/sessionGrouping.ts
new file mode 100644
index 000000000..7f10ba9ef
--- /dev/null
+++ b/frontend/src/components/sessionGrouping.ts
@@ -0,0 +1,277 @@
+// Pure logic for sidebar session grouping (replaces the old source filter).
+
+export type SessionGroupMode = 'none' | 'date'
+
+export const SESSION_GROUP_MODE_STORAGE_KEY = 'weknora:session-group-mode'
+export const DEFAULT_SESSION_GROUP_MODE: SessionGroupMode = 'none'
+
+/** Mirrors backend types.EmbedSessionMarkerPrefix */
+export const EMBED_SESSION_MARKER_PREFIX = 'embed_channel:'
+
+export interface SessionForGrouping {
+ id: string
+ title?: string
+ is_pinned?: boolean
+ created_at?: string
+ updated_at?: string
+ im_platform?: string
+ description?: string
+ originalIndex?: number
+}
+
+export interface SessionGroup<T extends SessionForGrouping = SessionForGrouping> {
+ key: string
+ label: string
+ items: T[]
+}
+
+export type SessionOrigin =
+ | { kind: 'web' }
+ | { kind: 'im'; platform: string }
+ | { kind: 'embed'; channelId: string }
+
+export interface GroupModeOption {
+ value: SessionGroupMode
+ label: string
+}
+
+export interface SourceGroupLabels {
+ web: string
+ embedFallback: string
+ embedChannel: (channelId: string) => string
+ imPlatform: (platform: string) => string
+}
+
+// Distinct platform keys from the tenant's IM channel overview, in first-seen order.
+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 function buildGroupModeOptions(labels: {
+ none: string
+ date: string
+}): GroupModeOption[] {
+ return [
+ { value: 'none', label: labels.none },
+ { value: 'date', label: labels.date },
+ ]
+}
+
+export function readStoredGroupMode(): SessionGroupMode {
+ if (typeof localStorage === 'undefined') return DEFAULT_SESSION_GROUP_MODE
+ const raw = localStorage.getItem(SESSION_GROUP_MODE_STORAGE_KEY)
+ if (raw === 'none' || raw === 'date') return raw
+ // Legacy "source" mode — channels are now separate folders like OpenAI projects.
+ if (raw === 'source') return 'none'
+ return DEFAULT_SESSION_GROUP_MODE
+}
+
+export function storeGroupMode(mode: SessionGroupMode): void {
+ if (typeof localStorage === 'undefined') return
+ localStorage.setItem(SESSION_GROUP_MODE_STORAGE_KEY, mode)
+}
+
+export function resolveSessionOrigin(session: SessionForGrouping): SessionOrigin {
+ const platform = (session.im_platform || '').trim().toLowerCase()
+ if (platform) return { kind: 'im', platform }
+ const desc = (session.description || '').trim()
+ if (desc.startsWith(EMBED_SESSION_MARKER_PREFIX)) {
+ const channelId = desc.slice(EMBED_SESSION_MARKER_PREFIX.length).trim()
+ if (channelId) return { kind: 'embed', channelId }
+ }
+ return { kind: 'web' }
+}
+
+export function originGroupKey(origin: SessionOrigin): string {
+ switch (origin.kind) {
+ case 'web':
+ return 'web'
+ case 'im':
+ return `im:${origin.platform}`
+ case 'embed':
+ return `embed:${origin.channelId}`
+ }
+}
+
+function labelForOrigin(
+ origin: SessionOrigin,
+ labels: SourceGroupLabels,
+ embedChannelNames: Record<string, string>,
+): string {
+ switch (origin.kind) {
+ case 'web':
+ return labels.web
+ case 'im':
+ return labels.imPlatform(origin.platform)
+ case 'embed': {
+ const name = embedChannelNames[origin.channelId]?.trim()
+ return name || labels.embedChannel(origin.channelId)
+ }
+ }
+}
+
+export function classifyDateBucket(dateStr: string | undefined): DateBucketKey {
+ if (!dateStr) return 'earlier'
+
+ const date = new Date(dateStr)
+ const now = new Date()
+ const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
+ const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
+ const sevenDaysAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
+ const thirtyDaysAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
+ const oneYearAgo = new Date(today.getTime() - 365 * 24 * 60 * 60 * 1000)
+ const sessionDate = new Date(date.getFullYear(), date.getMonth(), date.getDate())
+
+ if (sessionDate.getTime() >= today.getTime()) return 'today'
+ if (sessionDate.getTime() >= yesterday.getTime()) return 'yesterday'
+ if (date.getTime() >= sevenDaysAgo.getTime()) return 'last7Days'
+ if (date.getTime() >= thirtyDaysAgo.getTime()) return 'last30Days'
+ if (date.getTime() >= oneYearAgo.getTime()) return 'lastYear'
+ return 'earlier'
+}
+
+const DATE_BUCKET_ORDER = [
+ 'pinned',
+ 'today',
+ 'yesterday',
+ 'last7Days',
+ 'last30Days',
+ 'lastYear',
+ 'earlier',
+] as const
+
+export type DateBucketKey = (typeof DATE_BUCKET_ORDER)[number]
+
+export function groupSessionsByDate<T extends SessionForGrouping>(
+ sessions: T[],
+ bucketLabels: Record<DateBucketKey, string>,
+ categorize: (session: T) => DateBucketKey,
+): SessionGroup<T>[] {
+ const buckets = new Map<DateBucketKey, T[]>()
+ for (const key of DATE_BUCKET_ORDER) buckets.set(key, [])
+
+ for (const session of sessions) {
+ const bucket: DateBucketKey = session.is_pinned ? 'pinned' : categorize(session)
+ buckets.get(bucket)!.push(session)
+ }
+
+ return DATE_BUCKET_ORDER
+ .filter((key) => (buckets.get(key)?.length ?? 0) > 0)
+ .map((key) => ({
+ key,
+ label: bucketLabels[key],
+ items: buckets.get(key)!,
+ }))
+}
+
+export function groupSessionsBySource<T extends SessionForGrouping>(
+ sessions: T[],
+ labels: SourceGroupLabels,
+ embedChannelNames: Record<string, string>,
+ configuredImPlatforms: string[],
+ pinnedLabel: string,
+): SessionGroup<T>[] {
+ const pinned: T[] = []
+ const byKey = new Map<string, T[]>()
+
+ for (const session of sessions) {
+ if (session.is_pinned) {
+ pinned.push(session)
+ continue
+ }
+ const origin = resolveSessionOrigin(session)
+ const key = originGroupKey(origin)
+ if (!byKey.has(key)) byKey.set(key, [])
+ byKey.get(key)!.push(session)
+ }
+
+ const orderedKeys: string[] = []
+ if (byKey.has('web')) orderedKeys.push('web')
+
+ const seenIm = new Set<string>()
+ for (const platform of configuredImPlatforms) {
+ const key = `im:${platform}`
+ if (byKey.has(key)) {
+ orderedKeys.push(key)
+ seenIm.add(platform)
+ }
+ }
+ const extraIm = Array.from(byKey.keys())
+ .filter((k) => k.startsWith('im:') && !seenIm.has(k.slice(3)))
+ .sort((a, b) => a.localeCompare(b))
+ orderedKeys.push(...extraIm)
+
+ const embedKeys = Array.from(byKey.keys())
+ .filter((k) => k.startsWith('embed:'))
+ .sort((a, b) => {
+ const idA = a.slice(7)
+ const idB = b.slice(7)
+ const nameA = embedChannelNames[idA] || idA
+ const nameB = embedChannelNames[idB] || idB
+ return nameA.localeCompare(nameB)
+ })
+ orderedKeys.push(...embedKeys)
+
+ const groups: SessionGroup<T>[] = []
+ if (pinned.length > 0) {
+ groups.push({ key: 'pinned', label: pinnedLabel, items: pinned })
+ }
+ for (const key of orderedKeys) {
+ const items = byKey.get(key)
+ if (!items?.length) continue
+ const sample = items[0]
+ const origin = resolveSessionOrigin(sample)
+ groups.push({
+ key,
+ label: labelForOrigin(origin, labels, embedChannelNames),
+ items,
+ })
+ }
+ return groups
+}
+
+export function groupSessionsFlat<T extends SessionForGrouping>(
+ sessions: T[],
+ pinnedLabel: string,
+): SessionGroup<T>[] {
+ const pinned = sessions.filter((s) => s.is_pinned)
+ const rest = sessions.filter((s) => !s.is_pinned)
+ const groups: SessionGroup<T>[] = []
+ if (pinned.length > 0) groups.push({ key: 'pinned', label: pinnedLabel, items: pinned })
+ if (rest.length > 0) groups.push({ key: 'all', label: '', items: rest })
+ return groups
+}
+
+export function groupSessions<T extends SessionForGrouping>(
+ mode: SessionGroupMode,
+ sessions: T[],
+ opts: {
+ pinnedLabel: string
+ bucketLabels: Record<DateBucketKey, string>
+ categorizeDate: (session: T) => DateBucketKey
+ sourceLabels: SourceGroupLabels
+ embedChannelNames: Record<string, string>
+ configuredImPlatforms: string[]
+ },
+): SessionGroup<T>[] {
+ if (!sessions.length) return []
+ switch (mode) {
+ case 'none':
+ return groupSessionsFlat(sessions, opts.pinnedLabel)
+ case 'date':
+ default:
+ return groupSessionsByDate(sessions, opts.bucketLabels, opts.categorizeDate)
+ }
+}
+
+/** Chat list rows show source badges when channels live in separate folders. */
+export function shouldShowSessionSourceBadge(_mode: SessionGroupMode): boolean {
+ return false
+}
diff --git a/frontend/src/components/sessionSidebarBuckets.test.ts b/frontend/src/components/sessionSidebarBuckets.test.ts
new file mode 100644
index 000000000..e2d8fee42
--- /dev/null
+++ b/frontend/src/components/sessionSidebarBuckets.test.ts
@@ -0,0 +1,58 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ applyBucketCountProbe,
+ bucketVisible,
+ createEmptyBucket,
+ prependSessionToWebBucket,
+ type BucketDefinition,
+} from './sessionSidebarBuckets.ts'
+
+const imDef: BucketDefinition = {
+ key: 'im:feishu',
+ apiSource: 'feishu',
+ label: 'Feishu',
+ kind: 'im',
+ platform: 'feishu',
+}
+
+test('bucketVisible hides channel buckets until count is known', () => {
+ const bucket = createEmptyBucket(imDef)
+ assert.equal(bucketVisible(bucket), false)
+})
+
+test('bucketVisible hides channel buckets with zero sessions after probe', () => {
+ const bucket = applyBucketCountProbe(createEmptyBucket(imDef), 0)
+ assert.equal(bucketVisible(bucket), false)
+})
+
+test('bucketVisible shows channel buckets with sessions after probe', () => {
+ const bucket = applyBucketCountProbe(createEmptyBucket(imDef), 3)
+ assert.equal(bucketVisible(bucket), true)
+})
+
+test('prependSessionToWebBucket inserts new session at front and bumps total', () => {
+ const webDef: BucketDefinition = {
+ key: 'web',
+ apiSource: 'web',
+ label: 'Chats',
+ kind: 'web',
+ }
+ const bucket = { ...createEmptyBucket(webDef), total: 2, items: [{ id: 'a' }] }
+ const next = prependSessionToWebBucket(bucket, { id: 'b', title: 'New' })
+ assert.deepEqual(next.items.map((s) => s.id), ['b', 'a'])
+ assert.equal(next.total, 3)
+})
+
+test('prependSessionToWebBucket is idempotent for existing session', () => {
+ const webDef: BucketDefinition = {
+ key: 'web',
+ apiSource: 'web',
+ label: 'Chats',
+ kind: 'web',
+ }
+ const bucket = { ...createEmptyBucket(webDef), total: 1, items: [{ id: 'a' }] }
+ const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' })
+ assert.equal(next, bucket)
+})
diff --git a/frontend/src/components/sessionSidebarBuckets.ts b/frontend/src/components/sessionSidebarBuckets.ts
new file mode 100644
index 000000000..62da3faac
--- /dev/null
+++ b/frontend/src/components/sessionSidebarBuckets.ts
@@ -0,0 +1,172 @@
+// OpenAI-style sidebar: channel folders (IM / embed) + flat/date-grouped chats,
+// each bucket paginates independently via the API `source` param.
+
+import type { SessionForGrouping } from './sessionGrouping'
+
+export const SIDEBAR_BUCKET_PAGE_SIZE = 30
+
+export type SidebarBucketKind = 'web' | 'im' | 'embed'
+
+export interface SidebarSessionBucket {
+ key: string
+ apiSource: string
+ label: string
+ kind: SidebarBucketKind
+ platform?: string
+ page: number
+ total: number
+ items: SessionForGrouping[]
+ loaded: boolean
+ loading: boolean
+ /** 已通过轻量 count 探测(page_size=1),用于隐藏无会话的渠道文件夹 */
+ countKnown: boolean
+}
+
+export interface BucketDefinition {
+ key: string
+ apiSource: string
+ label: string
+ kind: SidebarBucketKind
+ platform?: string
+}
+
+export function createEmptyBucket(def: BucketDefinition): SidebarSessionBucket {
+ return {
+ ...def,
+ page: 0,
+ total: 0,
+ items: [],
+ loaded: false,
+ loading: false,
+ countKnown: false,
+ }
+}
+
+export function bucketHasMore(bucket: SidebarSessionBucket): boolean {
+ return bucket.items.length < bucket.total
+}
+
+export function bucketVisible(bucket: SidebarSessionBucket): boolean {
+ if (!isChannelBucket(bucket)) return true
+ if (!bucket.countKnown) return false
+ return bucket.total > 0
+}
+
+export function applyBucketCountProbe(
+ bucket: SidebarSessionBucket,
+ total: number,
+): SidebarSessionBucket {
+ return { ...bucket, total, countKnown: true }
+}
+
+export function isChannelBucket(bucket: SidebarSessionBucket): boolean {
+ return bucket.kind === 'im' || bucket.kind === 'embed'
+}
+
+export function isChannelBucketKey(key: string): boolean {
+ return key.startsWith('im:') || key.startsWith('embed:')
+}
+
+export function buildBucketDefinitions(
+ imPlatforms: string[],
+ embedChannels: Record<string, string>,
+ labels: {
+ web: string
+ imPlatform: (platform: string) => string
+ embedChannel: (name: string) => string
+ },
+): BucketDefinition[] {
+ const imDefs = imPlatforms.map((platform) => ({
+ key: `im:${platform}`,
+ apiSource: platform,
+ label: labels.imPlatform(platform),
+ kind: 'im' as const,
+ platform,
+ }))
+ const embedDefs = Object.entries(embedChannels).map(([id, name]) => ({
+ key: `embed:${id}`,
+ apiSource: `embed:${id}`,
+ label: labels.embedChannel(name || id.slice(0, 8)),
+ kind: 'embed' as const,
+ }))
+ return [
+ ...imDefs,
+ ...embedDefs,
+ {
+ key: 'web',
+ apiSource: 'web',
+ label: labels.web,
+ kind: 'web',
+ },
+ ]
+}
+
+export function mergeBucketPage(
+ bucket: SidebarSessionBucket,
+ rows: SessionForGrouping[],
+ total: number,
+ page: number,
+): SidebarSessionBucket {
+ const seen = new Set(bucket.items.map((s) => s.id))
+ const merged = [...bucket.items]
+ for (const row of rows) {
+ if (seen.has(row.id)) continue
+ seen.add(row.id)
+ merged.push(row)
+ }
+ return {
+ ...bucket,
+ page,
+ total,
+ items: merged,
+ loaded: true,
+ loading: false,
+ }
+}
+
+export function flattenBucketItems(
+ buckets: Record<string, SidebarSessionBucket>,
+ order: string[],
+): SessionForGrouping[] {
+ const out: SessionForGrouping[] = []
+ const seen = new Set<string>()
+ for (const key of order) {
+ const bucket = buckets[key]
+ if (!bucket) continue
+ for (const item of bucket.items) {
+ if (seen.has(item.id)) continue
+ seen.add(item.id)
+ out.push(item)
+ }
+ }
+ return out
+}
+
+export function prependSessionToWebBucket(
+ bucket: SidebarSessionBucket,
+ session: SessionForGrouping,
+): SidebarSessionBucket {
+ if (bucket.items.some((row) => row.id === session.id)) return bucket
+ return {
+ ...bucket,
+ items: [session, ...bucket.items],
+ total: bucket.total + 1,
+ loaded: true,
+ }
+}
+
+export function removeSessionFromBuckets(
+ buckets: Record<string, SidebarSessionBucket>,
+ sessionId: string,
+): Record<string, SidebarSessionBucket> {
+ const next: Record<string, SidebarSessionBucket> = {}
+ for (const [key, bucket] of Object.entries(buckets)) {
+ const items = bucket.items.filter((s) => s.id !== sessionId)
+ next[key] = {
+ ...bucket,
+ items,
+ total: Math.max(0, bucket.total - (items.length < bucket.items.length ? 1 : 0)),
+ }
+ }
+ return next
+}
diff --git a/frontend/src/components/sessionSourceFilter.test.ts b/frontend/src/components/sessionSourceFilter.test.ts
deleted file mode 100644
index 5a2c49a26..000000000
--- a/frontend/src/components/sessionSourceFilter.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-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
deleted file mode 100644
index ca1ad91c6..000000000
--- a/frontend/src/components/sessionSourceFilter.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-// 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 })),
- ]
-}
diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue
index f33a448fe..2c721a65d 100644
--- a/frontend/src/views/agent/AgentList.vue
+++ b/frontend/src/views/agent/AgentList.vue
@@ -1502,9 +1502,11 @@ const confirmDelete = () => {
})
}
-const handleEditorSuccess = () => {
- editorVisible.value = false
- editingAgent.value = null
+const handleEditorSuccess = (agent?: CustomAgent) => {
+ if (agent) {
+ editingAgent.value = agent
+ editorMode.value = 'edit'
+ }
fetchList(true)
}
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 6d9d1de81..c2cef9276 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -1,11 +1,11 @@
<template>
- <div ref="rootElement" class="agent-stream-display">
+ <div ref="rootElement" class="agent-stream-display" :class="{ 'is-embedded': embeddedMode }">
<!-- Collapsed intermediate steps (tree root) -->
<div v-if="shouldShowCollapsedSteps" class="tree-container">
<div class="tree-root" @click="toggleIntermediateSteps">
<div class="tree-root-title">
- <img :src="agentIcon" alt="" />
+ <span class="icon-mask tree-root-icon" :style="maskIconStyle(agentIcon, 16)" aria-hidden="true" />
<span v-html="intermediateStepsSummaryHtml"></span>
</div>
<div class="tree-root-toggle">
@@ -34,7 +34,7 @@
<div class="action-card" :class="{ 'action-pending': isThinkingActive(event.event_id) }">
<div class="action-header" @click="toggleEvent(event.event_id)">
<div class="action-title">
- <img class="action-title-icon" :src="thinkingIcon" alt="" />
+ <span class="action-title-icon icon-mask" :style="maskIconStyle(thinkingIcon)" aria-hidden="true" />
<span v-if="event.title" class="action-name action-preamble-title">{{ event.title }}</span>
<span v-else-if="isEventExpanded(event.event_id)" class="action-name">{{ $t('agent.think') }}</span>
<span v-else-if="getThinkingSummary(event)" class="action-summary">{{ getThinkingSummary(event) }}</span>
@@ -56,7 +56,7 @@
<div class="action-card" :class="{ 'action-pending': event.pending || isThinkingActive(event.tool_call_id) }">
<div class="action-header" @click="toggleEvent(event.tool_call_id)">
<div class="action-title">
- <img class="action-title-icon" :src="thinkingIcon" alt="" />
+ <span class="action-title-icon icon-mask" :style="maskIconStyle(thinkingIcon)" aria-hidden="true" />
<span class="action-name">{{ $t('agent.think') }}</span>
<span v-if="event.tool_data?.thought_number" class="action-badge">{{ event.tool_data.thought_number }}/{{ event.tool_data.total_thoughts }}</span>
<span v-if="getThinkingSummary(event) && !isEventExpanded(event.tool_call_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>
@@ -100,7 +100,12 @@
>
<div class="action-header" @click="handleActionHeaderClick(event)" :class="{ 'no-results': !hasResults(event) }">
<div class="action-title">
- <img v-if="event.tool_name && !isBookIcon(event.tool_name)" class="action-title-icon" :src="getToolIcon(event.tool_name)" alt="" />
+ <span
+ v-if="event.tool_name && !isBookIcon(event.tool_name)"
+ class="action-title-icon icon-mask"
+ :style="maskIconStyle(getToolIcon(event.tool_name))"
+ aria-hidden="true"
+ />
<t-icon v-if="event.tool_name && isBookIcon(event.tool_name)" class="action-title-icon" name="book" />
<t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps" :content="t('agent.updatePlan')" placement="top">
<span class="action-name">{{ $t('agent.updatePlan') }}</span>
@@ -184,7 +189,7 @@
<div class="action-card" :class="{ 'action-pending': isThinkingActive(event.event_id) }">
<div class="action-header" @click="toggleEvent(event.event_id)">
<div class="action-title">
- <img class="action-title-icon" :src="thinkingIcon" alt="" />
+ <span class="action-title-icon icon-mask" :style="maskIconStyle(thinkingIcon)" aria-hidden="true" />
<span v-if="event.title" class="action-name action-preamble-title">{{ event.title }}</span>
<span v-else class="action-name">{{ $t('agent.think') }}</span>
<span v-if="!event.title && getThinkingSummary(event) && !isEventExpanded(event.event_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>
@@ -222,7 +227,7 @@
<div class="action-card" :class="{ 'action-pending': event.pending || isThinkingActive(event.tool_call_id) }">
<div class="action-header" @click="toggleEvent(event.tool_call_id)">
<div class="action-title">
- <img class="action-title-icon" :src="thinkingIcon" alt="" />
+ <span class="action-title-icon icon-mask" :style="maskIconStyle(thinkingIcon)" aria-hidden="true" />
<span class="action-name">{{ $t('agent.think') }}</span>
<span v-if="event.tool_data?.thought_number" class="action-badge">{{ event.tool_data.thought_number }}/{{ event.tool_data.total_thoughts }}</span>
<span v-if="getThinkingSummary(event) && !isEventExpanded(event.tool_call_id)" class="action-summary">{{ getThinkingSummary(event) }}</span>
@@ -247,7 +252,7 @@
>
<div v-html="renderAnswerContent(event.content)"></div>
</div>
- <div v-if="event.done && event.content && event.content.trim()" class="answer-toolbar">
+ <div v-if="event.done && event.content && event.content.trim() && !embeddedMode" class="answer-toolbar">
<t-button size="small" variant="outline" shape="round" @click.stop="handleCopyAnswer(event)" :title="$t('agent.copy')">
<t-icon name="copy" />
</t-button>
@@ -278,7 +283,12 @@
>
<div class="action-header" @click="handleActionHeaderClick(event)" :class="{ 'no-results': !hasResults(event) }">
<div class="action-title">
- <img v-if="event.tool_name && !isBookIcon(event.tool_name)" class="action-title-icon" :src="getToolIcon(event.tool_name)" alt="" />
+ <span
+ v-if="event.tool_name && !isBookIcon(event.tool_name)"
+ class="action-title-icon icon-mask"
+ :style="maskIconStyle(getToolIcon(event.tool_name))"
+ aria-hidden="true"
+ />
<t-icon v-if="event.tool_name && isBookIcon(event.tool_name)" class="action-title-icon" name="book" />
<t-tooltip v-if="event.tool_name === 'todo_write' && event.tool_data?.steps" :content="t('agent.updatePlan')" placement="top">
<span class="action-name">
@@ -425,6 +435,7 @@ import ToolApprovalCard from './ToolApprovalCard.vue';
import ChatRequestInfoButton from '@/components/ChatRequestInfoButton.vue';
import picturePreview from '@/components/picture-preview.vue';
import { getChunkByIdOnly } from '@/api/knowledge-base';
+import { getEmbedChunkById } from '@/api/embed';
import { getRootZoom, rectToCssPx } from '@/utils/zoom';
import { getWikiPage, type WikiPage } from '@/api/wiki';
import { MessagePlugin } from 'tdesign-vue-next';
@@ -772,10 +783,10 @@ const openFloatForEl = (el: HTMLElement, widthAdjust = 120) => {
// Import icons
import agentIcon from '@/assets/img/agent.svg';
import thinkingIcon from '@/assets/img/Frame3718.svg';
-import knowledgeIcon from '@/assets/img/zhishiku-thin.svg';
+import knowledgeIcon from '@/assets/img/zhishiku.svg';
import documentIcon from '@/assets/img/ziliao.svg';
-import fileAddIcon from '@/assets/img/file-add-green.svg';
-import webSearchGlobeGreenIcon from '@/assets/img/websearch-globe-green.svg';
+import fileAddIcon from '@/assets/img/file-add.svg';
+import webSearchGlobeIcon from '@/assets/img/websearch-globe.svg';
interface SessionData {
id?: string;
@@ -790,9 +801,14 @@ const props = defineProps<{
session: SessionData;
sessionId?: string;
userQuery?: string;
+ embeddedMode?: boolean;
+ embedChannelId?: string;
+ embedToken?: string;
}>();
-const showRequestInfo = computed(() => !!(props.session?.request_id || props.session?.id));
+const showRequestInfo = computed(
+ () => !props.embeddedMode && !!(props.session?.request_id || props.session?.id),
+);
// Configure marked for security
marked.use({});
@@ -1526,7 +1542,9 @@ const loadChunkDetails = async (chunkId: string) => {
setKbCacheState(chunkId, { loading: true });
try {
- const response = await getChunkByIdOnly(chunkId);
+ const response = props.embeddedMode && props.embedChannelId && props.embedToken
+ ? await getEmbedChunkById(props.embedChannelId, props.embedToken, chunkId)
+ : await getChunkByIdOnly(chunkId);
const content = response.data?.content;
if (content) {
const html = buildKbTooltipContent(content);
@@ -2178,6 +2196,18 @@ const isBookIcon = (toolName: string): boolean => {
return false; // 不再使用 t-icon 的 book,改用 SVG 图标
};
+/** Render SVG assets in the channel / brand color via CSS mask. */
+function maskIconStyle(src: string, size = 14): Record<string, string> {
+ if (!src) return {}
+ const url = `url("${src}")`
+ return {
+ width: `${size}px`,
+ height: `${size}px`,
+ WebkitMaskImage: url,
+ maskImage: url,
+ }
+}
+
// Get icon for tool type
const getToolIcon = (toolName: string): string => {
if (toolName === 'thinking') {
@@ -2187,7 +2217,7 @@ const getToolIcon = (toolName: string): string => {
} else if (toolName === 'grep_chunks') {
return knowledgeIcon; // Use same icon as knowledge_search for consistency
} else if (toolName === 'web_search') {
- return webSearchGlobeGreenIcon;
+ return webSearchGlobeIcon;
} else if (toolName === 'get_document_info' || toolName === 'list_knowledge_chunks') {
return documentIcon;
} else if (toolName === 'todo_write') {
@@ -2517,6 +2547,34 @@ const handleAddToKnowledge = (answerEvent: any) => {
gap: 0;
margin-bottom: 10px;
position: relative;
+ --stream-brand-2: color-mix(in srgb, var(--td-brand-color) 2%, transparent);
+ --stream-brand-3: color-mix(in srgb, var(--td-brand-color) 3%, transparent);
+ --stream-brand-4: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
+ --stream-brand-5: color-mix(in srgb, var(--td-brand-color) 5%, transparent);
+ --stream-brand-6: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
+ --stream-brand-8: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
+ --stream-brand-10: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
+ --stream-brand-12: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
+ --stream-brand-15: color-mix(in srgb, var(--td-brand-color) 15%, transparent);
+ --stream-brand-20: color-mix(in srgb, var(--td-brand-color) 20%, transparent);
+
+ &.is-embedded {
+ margin-bottom: 0;
+
+ /* 与 EmbedChatCore 等待首包时的三点 loading 对齐 */
+ .loading-indicator {
+ height: 41px;
+ padding: 0 0 0 4px;
+ margin-top: 0;
+ animation: none;
+
+ .loading-typing span {
+ width: 6px;
+ height: 6px;
+ background: var(--embed-primary, var(--td-brand-color));
+ }
+ }
+ }
}
// Streaming steps container
@@ -2571,27 +2629,35 @@ const handleAddToKnowledge = (answerEvent: any) => {
border-radius: 8px;
background-color: var(--td-bg-color-container);
border: .5px solid var(--td-component-stroke);
- box-shadow: 0 2px 4px rgba(7, 192, 95, 0.08);
+ box-shadow: 0 2px 4px var(--stream-brand-8);
color: var(--td-text-color-primary);
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
&:hover {
- background-color: rgba(7, 192, 95, 0.04);
+ background-color: var(--stream-brand-4);
}
}
+.icon-mask {
+ display: inline-block;
+ flex-shrink: 0;
+ background-color: var(--td-brand-color);
+ mask-size: contain;
+ mask-repeat: no-repeat;
+ mask-position: center;
+ -webkit-mask-size: contain;
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-position: center;
+}
+
+.tree-root-icon {
+ margin-right: 8px;
+}
+
.tree-root-title {
display: flex;
align-items: center;
- img {
- width: 16px;
- height: 16px;
- color: var(--td-brand-color);
- fill: currentColor;
- margin-right: 8px;
- }
-
span {
white-space: nowrap;
font-size: 12px;
@@ -2712,7 +2778,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
/* keyboard focus */
:deep(.citation-web:focus-visible) {
- outline: 2px solid var(--td-success-color); /* green-400 */
+ outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
@@ -2852,7 +2918,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
&:hover {
border-color: var(--td-brand-color);
- box-shadow: 0 1px 4px rgba(7, 192, 95, 0.08);
+ box-shadow: 0 1px 4px var(--stream-brand-8);
}
&.action-error {
@@ -2862,8 +2928,8 @@ const handleAddToKnowledge = (answerEvent: any) => {
&.action-pending {
opacity: 1;
box-shadow: none;
- border-color: rgba(7, 192, 95, 0.15);
- background: linear-gradient(120deg, rgba(7, 192, 95, 0.01), var(--td-bg-color-container));
+ border-color: var(--stream-brand-15);
+ background: linear-gradient(120deg, var(--stream-brand-2), var(--td-bg-color-container));
&::after {
content: '';
@@ -2872,8 +2938,8 @@ const handleAddToKnowledge = (answerEvent: any) => {
background: linear-gradient(
120deg,
transparent 0%,
- rgba(7, 192, 95, 0.06) 40%,
- rgba(7, 192, 95, 0.08) 55%,
+ var(--stream-brand-6) 40%,
+ var(--stream-brand-8) 55%,
transparent 85%
);
transform: translateX(-100%);
@@ -2938,7 +3004,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
transition: background-color 0.15s ease;
&:hover {
- background-color: rgba(7, 192, 95, 0.03);
+ background-color: var(--stream-brand-3);
}
&.no-results {
@@ -2958,17 +3024,12 @@ const handleAddToKnowledge = (answerEvent: any) => {
min-width: 0;
.action-title-icon {
- width: 14px;
- height: 14px;
- color: var(--td-brand-color);
- fill: currentColor;
flex-shrink: 0;
-
- :deep(svg) {
+
+ &.t-icon {
width: 14px;
height: 14px;
color: var(--td-brand-color);
- fill: currentColor;
}
}
@@ -2999,7 +3060,7 @@ const handleAddToKnowledge = (answerEvent: any) => {
padding: 0 6px;
height: 18px;
border-radius: 9px;
- background: rgba(7, 192, 95, 0.10);
+ background: var(--stream-brand-10);
color: var(--td-brand-color);
font-size: 11px;
font-weight: 500;
@@ -3104,11 +3165,11 @@ const handleAddToKnowledge = (answerEvent: any) => {
@keyframes pulseBorder {
0%, 100% {
border-left-color: var(--td-brand-color);
- box-shadow: 0 1px 3px rgba(7, 192, 95, 0.06);
+ box-shadow: 0 1px 3px var(--stream-brand-6);
}
50% {
border-left-color: var(--td-brand-color);
- box-shadow: 0 1px 4px rgba(7, 192, 95, 0.12);
+ box-shadow: 0 1px 4px var(--stream-brand-12);
}
}
@@ -3243,9 +3304,9 @@ const handleAddToKnowledge = (answerEvent: any) => {
.plan-task-change-card {
padding: 8px 12px;
- background: linear-gradient(135deg, rgba(7, 192, 95, 0.05), rgba(7, 192, 95, 0.02));
+ background: linear-gradient(135deg, var(--stream-brand-5), var(--stream-brand-2));
border-radius: 6px;
- border: 1px solid rgba(7, 192, 95, 0.2);
+ border: 1px solid var(--stream-brand-20);
font-size: 12px;
color: var(--td-text-color-primary);
@@ -3341,20 +3402,18 @@ const handleAddToKnowledge = (answerEvent: any) => {
}
:deep(.citation-web) {
- /* Align with app primary green scheme */
- background: var(--td-success-color-light); /* green-50 */
- color: var(--td-success-color); /* green-800 */
- border: 1px solid var(--td-success-color-focus); /* green-200 */
+ background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
+ color: var(--td-brand-color);
+ border: 1px solid color-mix(in srgb, var(--td-brand-color) 20%, transparent);
cursor: pointer;
white-space: nowrap;
position: relative;
}
:deep(.citation-web:hover) {
- /* Subtle hover in green tone */
- background: var(--td-success-color-light); /* green-100 */
- border-color: var(--td-success-color); /* green-300 */
- color: var(--td-success-color); /* keep readable on light bg */
+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
+ border-color: var(--td-brand-color);
+ color: var(--td-brand-color);
}
/* Embedded tooltip bubble - hidden, use global floatPopup instead */
@@ -3373,17 +3432,29 @@ const handleAddToKnowledge = (answerEvent: any) => {
background-repeat: no-repeat;
background-size: contain;
background-position: center;
+ mask-size: contain;
+ mask-repeat: no-repeat;
+ mask-position: center;
+ -webkit-mask-size: contain;
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-position: center;
flex-shrink: 0;
}
/* Web icon (globe) */
:deep(.citation .citation-icon.web) {
- background-image: url("../../../assets/img/websearch-globe-green.svg");
+ background-image: none;
+ background-color: var(--td-brand-color);
+ mask-image: url("../../../assets/img/websearch-globe.svg");
+ -webkit-mask-image: url("../../../assets/img/websearch-globe.svg");
}
/* Knowledge base icon */
:deep(.citation .citation-icon.kb) {
- background-image: url("../../../assets/img/zhishiku-thin.svg");
+ background-image: none;
+ background-color: var(--td-brand-color);
+ mask-image: url("../../../assets/img/zhishiku.svg");
+ -webkit-mask-image: url("../../../assets/img/zhishiku.svg");
}
.kb-float-popup {
@@ -3449,12 +3520,11 @@ const handleAddToKnowledge = (answerEvent: any) => {
overflow-x: hidden;
}
-/* KB citation styles - same green theme as web citations */
+/* KB citation pill — follow brand / embed primary */
:deep(.citation.citation-kb) {
- /* Green theme - same as web citations */
- background: var(--td-success-color-light); /* green-50 */
- color: var(--td-success-color); /* green-800 */
- border: 1px solid var(--td-success-color-focus); /* green-200 */
+ background: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
+ color: var(--td-brand-color);
+ border: 1px solid color-mix(in srgb, var(--td-brand-color) 20%, transparent);
cursor: pointer;
white-space: nowrap;
position: relative;
@@ -3462,14 +3532,13 @@ const handleAddToKnowledge = (answerEvent: any) => {
}
:deep(.citation.citation-kb:hover) {
- /* Subtle hover in green tone */
- background: var(--td-success-color-light); /* green-100 */
- border-color: var(--td-success-color); /* green-300 */
- color: var(--td-success-color); /* keep readable on light bg */
+ background: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
+ border-color: var(--td-brand-color);
+ color: var(--td-brand-color);
}
:deep(.citation.citation-kb:focus-visible) {
- outline: 2px solid var(--td-success-color); /* green-400 */
+ outline: 2px solid var(--td-brand-color);
outline-offset: 2px;
}
@@ -3807,9 +3876,4 @@ const handleAddToKnowledge = (answerEvent: any) => {
}
}
}
-// Dark mode: invert agent icon (uses currentColor which doesn't work in <img>)
-html[theme-mode="dark"] .tree-root-title img {
- filter: invert(1);
- opacity: 0.55;
-}
</style>
diff --git a/frontend/src/views/chat/components/deepThink.vue b/frontend/src/views/chat/components/deepThink.vue
index 80002913a..2689b59ed 100644
--- a/frontend/src/views/chat/components/deepThink.vue
+++ b/frontend/src/views/chat/components/deepThink.vue
@@ -88,7 +88,7 @@ const toggleFold = () => {
border-radius: 8px;
background-color: var(--td-bg-color-container);
border: .5px solid var(--td-component-stroke);
- box-shadow: 0 2px 4px rgba(7, 192, 95, 0.08);
+ box-shadow: 0 2px 4px color-mix(in srgb, var(--td-brand-color) 8%, transparent);
overflow: hidden;
box-sizing: border-box;
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
@@ -105,7 +105,7 @@ const toggleFold = () => {
user-select: none;
&:hover {
- background-color: rgba(7, 192, 95, 0.04);
+ background-color: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
}
.think-title {
diff --git a/frontend/src/views/chat/components/docInfo.vue b/frontend/src/views/chat/components/docInfo.vue
index 1e1e84e24..b6d2020f2 100644
--- a/frontend/src/views/chat/components/docInfo.vue
+++ b/frontend/src/views/chat/components/docInfo.vue
@@ -2,7 +2,7 @@
<div class="refer" v-if="session.knowledge_references && session.knowledge_references.length">
<div class="refer_header" @click="referBoxSwitch">
<div class="refer_title">
- <img src="@/assets/img/ziliao.svg" :alt="$t('chat.referenceIconAlt')" />
+ <span class="refer-title-icon icon-mask" aria-hidden="true" />
<span>{{ headerText }}</span>
</div>
<div class="refer_show_icon">
@@ -32,7 +32,7 @@
<span class="doc-group-title" :title="group.title">{{ group.title }}</span>
<span class="doc-group-count">{{ $t('chat.referenceChunkCount', { count: group.chunks.length }) }}</span>
</div>
- <div class="doc-group-actions" v-if="group.knowledgeBaseId" @click.stop>
+ <div class="doc-group-actions" v-if="!embeddedMode && group.knowledgeBaseId" @click.stop>
<t-tooltip :content="$t('chat.navigateToDocument')">
<span class="doc-group-navigate" @click="navigateToDocument(group)">
<t-icon name="jump" size="14px" />
@@ -75,6 +75,10 @@ const props = defineProps({
session: {
type: Object,
required: false
+ },
+ embeddedMode: {
+ type: Boolean,
+ default: false
}
});
@@ -189,6 +193,10 @@ const getWebSearchDisplayText = (item) => {
</script>
<style lang="less" scoped>
.refer {
+ --refer-brand-4: color-mix(in srgb, var(--td-brand-color) 4%, transparent);
+ --refer-brand-8: color-mix(in srgb, var(--td-brand-color) 8%, transparent);
+ --refer-brand-12: color-mix(in srgb, var(--td-brand-color) 12%, transparent);
+
display: flex;
flex-direction: column;
font-size: 12px;
@@ -196,7 +204,7 @@ const getWebSearchDisplayText = (item) => {
border-radius: 8px;
background-color: var(--td-bg-color-container);
border: .5px solid var(--td-component-stroke);
- box-shadow: 0 2px 4px rgba(7, 192, 95, 0.08);
+ box-shadow: 0 2px 4px var(--refer-brand-8);
box-sizing: border-box;
overflow: hidden;
box-sizing: border-box;
@@ -215,14 +223,6 @@ const getWebSearchDisplayText = (item) => {
display: flex;
align-items: center;
- img {
- width: 16px;
- height: 16px;
- color: var(--td-brand-color);
- fill: currentColor;
- margin-right: 8px;
- }
-
span {
white-space: nowrap;
font-size: 12px;
@@ -237,7 +237,7 @@ const getWebSearchDisplayText = (item) => {
}
.refer_header:hover {
- background-color: rgba(7, 192, 95, 0.04);
+ background-color: var(--refer-brand-4);
cursor: pointer;
}
@@ -248,6 +248,26 @@ const getWebSearchDisplayText = (item) => {
}
}
+.icon-mask {
+ display: inline-block;
+ flex-shrink: 0;
+ background-color: var(--embed-primary, var(--td-brand-color));
+ mask-size: contain;
+ mask-repeat: no-repeat;
+ mask-position: center;
+ -webkit-mask-size: contain;
+ -webkit-mask-repeat: no-repeat;
+ -webkit-mask-position: center;
+}
+
+.refer-title-icon {
+ width: 16px;
+ height: 16px;
+ margin-right: 8px;
+ mask-image: url('@/assets/img/ziliao.svg');
+ -webkit-mask-image: url('@/assets/img/ziliao.svg');
+}
+
.doc {
text-decoration: none;
color: var(--td-brand-color);
@@ -263,7 +283,7 @@ const getWebSearchDisplayText = (item) => {
border-bottom: 1px dashed var(--td-brand-color);
&:hover {
- background-color: rgba(7, 192, 95, 0.08);
+ background-color: var(--refer-brand-8);
border-radius: 3px;
padding-right: 4px;
}
@@ -287,7 +307,7 @@ const getWebSearchDisplayText = (item) => {
transition: background-color 0.15s ease;
&:hover {
- background-color: rgba(7, 192, 95, 0.04);
+ background-color: var(--refer-brand-4);
}
.doc-group-left {
@@ -343,7 +363,7 @@ const getWebSearchDisplayText = (item) => {
transition: all 0.15s ease;
&:hover {
- background-color: var(--td-brand-color-light);
+ background-color: var(--refer-brand-12);
}
}
}
@@ -368,7 +388,7 @@ const getWebSearchDisplayText = (item) => {
white-space: nowrap;
&:hover {
- background-color: rgba(7, 192, 95, 0.04);
+ background-color: var(--refer-brand-4);
color: var(--td-brand-color);
}
diff --git a/frontend/src/views/chat/components/tool-results/PlanDisplay.vue b/frontend/src/views/chat/components/tool-results/PlanDisplay.vue
index 5fa19f3bd..e342409c0 100644
--- a/frontend/src/views/chat/components/tool-results/PlanDisplay.vue
+++ b/frontend/src/views/chat/components/tool-results/PlanDisplay.vue
@@ -4,11 +4,11 @@
<div v-for="(step, index) in data.steps" :key="step.id || index" class="step-item" :class="`status-${step.status}`">
<div class="step-checkbox" :class="{ 'checked': step.status === 'completed', 'in-progress': step.status === 'in_progress' }">
<svg v-if="step.status === 'completed'" width="16" height="16" viewBox="0 0 16 16" fill="none">
- <rect x="2" y="2" width="12" height="12" rx="2" fill="#07C05F"/>
- <path d="M5 8L7 10L11 6" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
+ <rect x="2" y="2" width="12" height="12" rx="2" fill="currentColor" />
+ <path d="M5 8L7 10L11 6" stroke="#fff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<svg v-else width="16" height="16" viewBox="0 0 16 16" fill="none">
- <rect x="2" y="2" width="12" height="12" rx="2" stroke="#d1d5db" stroke-width="1.5" fill="none"/>
+ <rect x="2" y="2" width="12" height="12" rx="2" stroke="currentColor" stroke-width="1.5" fill="none" />
</svg>
</div>
<span class="step-description" :class="{ 'completed': step.status === 'completed' }">
@@ -79,21 +79,17 @@ const props = defineProps<Props>();
display: flex;
align-items: center;
justify-content: center;
-
+ color: var(--td-text-color-placeholder);
+
&.checked {
- svg {
- rect {
- fill: var(--td-brand-color);
- }
- }
+ color: var(--embed-primary, var(--td-brand-color));
}
-
+
&.in-progress {
- svg {
- rect {
- stroke: var(--td-brand-color);
- stroke-width: 2;
- }
+ color: var(--embed-primary, var(--td-brand-color));
+
+ svg rect {
+ stroke-width: 2;
}
}
}
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 0251e5815..cb9628168 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -18,7 +18,7 @@
</div>
</div>
<!-- 推荐问题卡片 - 仅在新会话(无消息)时展示 -->
- <div v-if="messagesList.length === 0 && !loading" class="suggested-questions-container" :class="{ 'has-questions': suggestedQuestions.length > 0 || suggestedQuestionsLoading }">
+ <div v-if="!embeddedMode && messagesList.length === 0 && !loading" class="suggested-questions-container" :class="{ 'has-questions': suggestedQuestions.length > 0 || suggestedQuestionsLoading }">
<!-- 骨架屏占位 -->
<div v-if="suggestedQuestionsLoading && suggestedQuestions.length === 0" class="suggested-questions-inner">
<div class="suggested-questions-title"><t-skeleton animation="gradient" :row-col="[{ width: '120px', height: '18px' }]" /></div>
@@ -106,12 +106,12 @@
</template>
<script setup>
import { storeToRefs } from 'pinia';
-import { ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, markRaw, onBeforeUnmount, defineProps } from 'vue';
-import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
+import { ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, defineProps } from 'vue';
+import { useRoute, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import InputField from '../../components/Input-field.vue';
import botmsg from './components/botmsg.vue';
import usermsg from './components/usermsg.vue';
-import { getMessageList, generateSessionsTitle, getSession } from "@/api/chat/index";
+import { getMessageList, getSession } from "@/api/chat/index";
import { getSuggestedQuestions } from "@/api/agent/index";
import { useStream } from '../../api/chat/streame'
import { useMenuStore } from '@/stores/menu';
@@ -121,12 +121,13 @@ import { useI18n } from 'vue-i18n';
import { useUIStore } from '@/stores/ui';
import KnowledgeBaseEditorModal from '@/views/knowledge/KnowledgeBaseEditorModal.vue';
import { useKnowledgeBaseCreationNavigation } from '@/hooks/useKnowledgeBaseCreationNavigation';
+import { useChatStreamHandler } from '@/composables/useChatStreamHandler';
const props = defineProps({
session_id: { type: String, default: '' },
agentId: { type: String, default: '' },
kbIds: { type: Array, default: () => [] },
- embeddedMode: { type: Boolean, default: false }
+ embeddedMode: { type: Boolean, default: false },
});
const usemenuStore = useMenuStore();
@@ -140,29 +141,11 @@ const isAgentStreamSession = () => {
return useSettingsStoreInstance.isAgentEnabled;
};
-const ensureAgentMessageShell = (message, requestId) => {
- message.isAgentMode = true;
- if (!message.agentEventStream) message.agentEventStream = [];
- if (!message._eventMap) message._eventMap = new Map();
- if (!message._pendingToolCalls) message._pendingToolCalls = new Map();
- if (requestId) {
- if (!message.id) message.id = requestId;
- if (!message.request_id) message.request_id = requestId;
- }
-};
-
-// Agent 占位消息在 agent_query 时仅有空 eventStream。若立刻渲染 botmsg,会把列表
-// 底部的全局 Loading 顶下去造成跳动;等有首个事件再渲染,Loading 位置保持稳定。
-const shouldRenderAssistantMessage = (session) => {
- if (!session?.isAgentMode) return true;
- const stream = session.agentEventStream;
- return Array.isArray(stream) && stream.length > 0;
-};
const uiStore = useUIStore();
const { navigateToKnowledgeBaseList } = useKnowledgeBaseCreationNavigation();
const { t } = useI18n();
-const { menuArr, isFirstSession, firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles } = storeToRefs(usemenuStore);
-const { output, onChunk, isStreaming, isLoading, error, startStream, stopStream, lastStreamRequest } = useStream();
+const { firstQuery, firstMentionedItems, firstModelId, firstImageFiles, firstAttachmentFiles } = storeToRefs(usemenuStore);
+const { onChunk, error, startStream, stopStream, lastStreamRequest } = useStream();
/** Snapshot of the in-flight HTTP request for attaching to the next assistant message. */
const pendingStreamDebug = ref(null);
@@ -189,9 +172,7 @@ const attachStreamDebugToMessage = (message) => {
message.debugRequest = payload;
};
const route = useRoute();
-const router = useRouter();
const session_id = ref(props.session_id || route.params.chatid);
-const sessionData = ref(null);
// 拉 session 详情,并按其 last_request_state 把输入栏状态恢复到当时的发起态。
// 嵌入式(embeddedMode)由宿主页面注入 agent/KB,所以跳过整套恢复逻辑,
@@ -201,7 +182,6 @@ const loadSessionAndHydrate = async (sid) => {
try {
const sessionRes = await getSession(sid);
if (sessionRes?.data) {
- sessionData.value = sessionRes.data;
const lastState = sessionRes.data.last_request_state;
if (lastState) {
// 先把当前的"全局默认"快照下来,再用 session 状态覆盖;
@@ -231,14 +211,12 @@ let recoverPollTimer = null;
// isn't a silent gap. IM-only: false everywhere else, so other flows are unchanged.
const isImRecovering = ref(false);
const scrollLock = ref(false);
-const isNeedTitle = ref(false);
const isFirstEnter = ref(true);
const loading = ref(false);
const historyLoading = ref(true);
const historyLoadingMore = ref(false);
const hasMoreHistory = ref(true);
let fullContent = ref('')
-let userquery = ref('')
const scrollContainer = ref(null)
const userHasScrolledUp = ref(false)
const SCROLL_BOTTOM_THRESHOLD = 80
@@ -270,6 +248,7 @@ const cancelSuggestedQuestionsFetch = () => {
};
const fetchSuggestedQuestionsIfNeeded = async () => {
+ if (props.embeddedMode) return;
// 初始历史尚未拉完时不能判断是否有消息,避免有历史的会话误请求推荐问法
if (historyLoading.value || messagesList.length > 0) {
if (messagesList.length > 0) {
@@ -288,10 +267,10 @@ const fetchSuggestedQuestions = async () => {
suggestedQuestionsLoading.value = true;
// 加载期间保留旧数据,不清空,避免布局抖动
try {
- const agentId = props.embeddedMode ? props.agentId : useSettingsStoreInstance.selectedAgentId;
+ const agentId = useSettingsStoreInstance.selectedAgentId;
if (!agentId) return;
- const selectedKBs = props.embeddedMode ? props.kbIds : useSettingsStoreInstance.getSelectedKnowledgeBases();
- const selectedFiles = props.embeddedMode ? [] : useSettingsStoreInstance.getSelectedFiles();
+ const selectedKBs = useSettingsStoreInstance.getSelectedKnowledgeBases();
+ const selectedFiles = useSettingsStoreInstance.getSelectedFiles();
const res = await getSuggestedQuestions(agentId, {
knowledge_base_ids: selectedKBs.length > 0 ? selectedKBs : undefined,
knowledge_ids: selectedFiles.length > 0 ? selectedFiles : undefined,
@@ -363,15 +342,6 @@ const getUserQuery = (index) => {
return '';
};
-const findLastMessage = (predicate) => {
- for (let i = messagesList.length - 1; i >= 0; i--) {
- const item = messagesList[i];
- if (predicate(item)) {
- return item;
- }
- }
- return undefined;
-};
watch([() => route.params], async (newvalue) => {
isFirstEnter.value = true;
if (newvalue[0].chatid) {
@@ -395,7 +365,6 @@ watch([() => route.params], async (newvalue) => {
// 并应用自己的 last_request_state(在 loadSessionAndHydrate 内部完成)。
useSettingsStoreInstance.restoreDefaultsIfSnapshotted();
- checkmenuTitle(session_id.value)
await loadSessionAndHydrate(session_id.value);
let data = {
session_id: session_id.value,
@@ -444,12 +413,80 @@ const handleScroll = () => {
debouncedScrollTop();
};
+const fetchMessageList = (data) => getMessageList(data);
+
+const {
+ findLastMessage,
+ shouldRenderAssistantMessage,
+ handleMsgList,
+ processStreamChunk,
+} = useChatStreamHandler({
+ messagesList,
+ loading,
+ isReplying,
+ currentAssistantMessageId,
+ fullContent,
+ isAgentStreamSession,
+ scrollToBottom,
+ onError: (msg) => MessagePlugin.error(msg),
+ preserveIncompleteStreamReactive: true,
+ isFirstEnter,
+ scrollContainer,
+ debug: import.meta.env.DEV,
+ onAfterMsgList: async () => {
+ const lastMessage = messagesList[messagesList.length - 1];
+ if (lastMessage && !lastMessage.is_completed) {
+ isReplying.value = true;
+ if (lastMessage.role === 'assistant') {
+ currentAssistantMessageId.value = lastMessage.id;
+ console.log('[Continue Stream] Set assistant message ID:', lastMessage.id);
+ }
+ // Only IM-originated replies (channel === 'im') get the quiet poll-to-recover
+ // path: their answer is generated on the IM side and never streams through
+ // this server, so continue-stream always 404s even though the reply *is*
+ // coming. Web/api replies keep the original behaviour (a real failure to
+ // resume the stream still surfaces as an error) — we don't touch them.
+ isAttachingImStream.value = lastMessage.channel === 'im';
+ await startStream({
+ session_id: session_id.value,
+ query: lastMessage.id,
+ method: 'GET',
+ url: '/api/v1/sessions/continue-stream',
+ });
+ // On success the stream resumed normally; on failure the error watcher
+ // already took over (quiet recovery for IM), so only clear the flag here.
+ if (!error.value) isAttachingImStream.value = false;
+ }
+ },
+ onAgentQuery: (data, existingMessage) => {
+ pendingStreamDebug.value = buildStreamDebugPayload();
+ if (data.id) {
+ const earlyMsg = findLastMessage((item) => item.role === 'assistant' && !item.is_completed);
+ if (earlyMsg) attachStreamDebugToMessage(earlyMsg);
+ }
+ if (existingMessage) attachStreamDebugToMessage(existingMessage);
+ },
+ onMessageCreated: (message) => attachStreamDebugToMessage(message),
+ onMessageUpdated: (message, payload) => {
+ attachStreamDebugToMessage(message);
+ if (payload?.is_completed) pendingStreamDebug.value = null;
+ },
+ onAgentAnswerDone: (message) => {
+ attachStreamDebugToMessage(message);
+ pendingStreamDebug.value = null;
+ },
+ onAgentChunkBound: (message) => {
+ attachStreamDebugToMessage(message);
+ pendingStreamDebug.value = null;
+ },
+});
+
const getmsgList = (data, isScrollType = false, scrollHeight) => {
if (isScrollType) {
if (historyLoadingMore.value || !hasMoreHistory.value) return;
historyLoadingMore.value = true;
}
- getMessageList(data).then(async (res) => {
+ fetchMessageList(data).then(async (res) => {
const batch = res?.data;
if (!batch?.length) {
if (isScrollType) {
@@ -484,246 +521,6 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
})
}
-// Recompose the visible answer from the agent event stream: concatenate every
-// non-superseded `answer` event, in arrival order. Superseded events are
-// per-round preambles that were retracted from the answer area (and relocated
-// into the steps tree), so they must not leak into message.content.
-const recomposeAgentAnswer = (message) => {
- if (!message.agentEventStream) return '';
- let out = '';
- for (const e of message.agentEventStream) {
- if (e.type === 'answer' && !e.superseded && e.content) {
- out += e.content;
- }
- }
- return out;
-};
-
-// Reconstruct agentEventStream from agent_steps stored in database
-// This allows the frontend to restore the exact conversation state including all agent reasoning steps
-const reconstructEventStreamFromSteps = (agentSteps, messageContent, isCompleted = false, isFallback = false, agentDurationMs = 0) => {
- const events = [];
-
- // Process agent steps if they exist
- if (agentSteps && Array.isArray(agentSteps) && agentSteps.length > 0) {
- agentSteps.forEach((step) => {
- // Compute step timestamp (milliseconds) from step.timestamp if available
- const stepTimestamp = step.timestamp ? new Date(step.timestamp).getTime() : 0;
-
- const hasToolCalls = step.tool_calls && Array.isArray(step.tool_calls) && step.tool_calls.length > 0;
-
- // Mirror what the user saw live, as two channels of one round (same
- // order as live: reasoning streams before the plain-content preamble):
- // - `reasoning_content` (e.g. DeepSeek / MiMo thinking-mode) → the
- // thinking card body.
- // - plain `content` narration (`step.thought`) → only a preamble when
- // this round went on to call tools. We replay it as a *superseded*
- // answer event, exactly like the live supersede signal, so
- // buildFullEventList relocates it into this round's thinking card
- // (as its title) instead of the answer area. For a terminal round
- // (no tool calls) `step.thought` is the final answer itself and
- // already lives in messageContent, so we never duplicate it here.
- const reasoningText = step.reasoning_content && step.reasoning_content.trim()
- ? step.reasoning_content
- : '';
- if (reasoningText) {
- events.push({
- type: 'thinking',
- event_id: `step-${step.iteration}-thought`,
- content: reasoningText,
- done: true,
- thinking: false,
- timestamp: stepTimestamp || undefined,
- duration_ms: step.duration || undefined,
- });
- }
- const preambleText = step.thought && step.thought.trim() ? step.thought : '';
- if (preambleText && hasToolCalls) {
- events.push({
- type: 'answer',
- event_id: `step-${step.iteration}-preamble`,
- content: preambleText,
- done: true,
- superseded: true,
- timestamp: stepTimestamp || undefined,
- });
- }
-
- // Add tool call and result events. Legacy histories may still contain a
- // final_answer tool call (the tool has since been removed); skip it since
- // its content is replayed as the answer event.
- if (step.tool_calls && Array.isArray(step.tool_calls)) {
- step.tool_calls.forEach((toolCall) => {
- if (toolCall.name === 'final_answer') return; // legacy data — shown as answer event
- events.push({
- type: 'tool_call',
- tool_call_id: toolCall.id,
- tool_name: toolCall.name,
- arguments: toolCall.args,
- pending: false,
- success: toolCall.result?.success !== false,
- output: toolCall.result?.output || '',
- error: toolCall.result?.error || undefined,
- timestamp: stepTimestamp || undefined,
- // Use both duration and duration_ms for compatibility
- duration: toolCall.duration,
- duration_ms: toolCall.duration,
- display_type: toolCall.result?.data?.display_type,
- tool_data: toolCall.result?.data,
- });
- });
- }
- });
- }
-
- // Add agent_complete event with duration info (before answer event)
- if (agentDurationMs > 0) {
- events.push({
- type: 'agent_complete',
- total_duration_ms: agentDurationMs,
- });
- }
-
- // 总是添加 answer 事件如果有内容(无论是否有 agent_steps)
- // 这样可以确保最终答案始终被渲染
- if (messageContent && messageContent.trim()) {
- const answerEvent = {
- type: 'answer',
- content: messageContent,
- done: true
- };
- if (isFallback) answerEvent.is_fallback = true;
- events.push(answerEvent);
- } else if (isCompleted) {
- // 消息已完成但 content 为空:说明是"停止时尚未产出最终答案"的场景。
- // Push 一个 stop 事件,让 AgentStreamDisplay 的 isConversationDone 返回 true,
- // 但不产生 answer 内容,也就不会渲染最终答案的 toolbar。与实时 stop 分支保持一致。
- events.push({
- type: 'stop',
- timestamp: Date.now(),
- reason: 'user_requested'
- });
- }
-
- return events;
-};
-const handleMsgList = async (data, isScrollType = false, newScrollHeight) => {
- // API 返回 created_at 升序(同秒时 user 在 assistant 前),保持该顺序渲染。
- const chatlist = [...data];
- const existingIds = new Set(messagesList.map(m => m.id).filter(Boolean));
- const processed = [];
- for (let i = 0, len = chatlist.length; i < len; i++) {
- let item = chatlist[i];
- if (item.id && existingIds.has(item.id)) {
- continue;
- }
- if (item.id) {
- existingIds.add(item.id);
- }
- item.isAgentMode = false; // Agent 模式标记
- // 历史消息的 agent_steps / agentEventStream 体量大、嵌套深,且是只读的,
- // 用 markRaw 跳过 Vue 的深响应式转换,避免一次性 unshift 多条时主线程被 Proxy 转换卡住造成白屏。
- //
- // 例外:最后一条「未完成」的消息会通过 continue-stream 继续增量推流,
- // handleAgentChunk 会持续 push/改写 agentEventStream、_eventMap、_pendingToolCalls。
- // 若对它 markRaw,Vue 不会追踪这些变更,前端就「后台在推但不渲染」(只能看到刷新前的快照),
- // 直到生成结束再次刷新才从 agent_steps 静态重建出完整内容。因此这条保持响应式。
- const willContinueStream = !item.is_completed;
- if (willContinueStream) {
- item.agentEventStream = item.agentEventStream || [];
- item._eventMap = new Map();
- item._pendingToolCalls = new Map();
- } else {
- item.agent_steps = item.agent_steps ? markRaw(item.agent_steps) : item.agent_steps;
- item.agentEventStream = markRaw(item.agentEventStream || []);
- item._eventMap = markRaw(new Map());
- item._pendingToolCalls = markRaw(new Map());
- }
-
- // Check if this message has agent_steps from database (historical agent conversation)
- // If so, reconstruct the agentEventStream to restore the exact conversation state
- if (item.agent_steps && Array.isArray(item.agent_steps) && item.agent_steps.length > 0) {
- item.isAgentMode = true;
- item.agentEventStream = markRaw(reconstructEventStreamFromSteps(item.agent_steps, item.content, item.is_completed, item.is_fallback, item.agent_duration_ms || 0));
- // 隐藏最终答案内容,因为它已经包含在 agentEventStream 的 answer 事件中
- item.hideContent = true;
- }
-
- if (item.content) {
- const thinkCloseTag = '</think>';
- if (!item.content.includes('<think>') && !item.content.includes(thinkCloseTag)) {
- item.thinkContent = "";
- item.content = item.content;
- item.showThink = false;
- item.thinking = false;
- } else if (item.content.includes(thinkCloseTag)) {
- // 历史消息中包含完整的 <think>...</think> 标签,说明 thinking 已完成
- item.showThink = true;
- item.thinking = false; // 关键:标记 thinking 已完成,使 deepThink 默认折叠
- const index = item.content.trim().lastIndexOf(thinkCloseTag);
- item.thinkContent = item.content.trim().substring(0, index).replace('<think>', '').trim();
- item.content = item.content.trim().substring(index + thinkCloseTag.length);
- } else if (item.content.includes('<think>')) {
- // 内容包含 <think> 但没有 </think>,说明 thinking 还在进行中(不太可能出现在历史消息中)
- item.showThink = true;
- item.thinking = true;
- item.thinkContent = item.content.replace('<think>', '').trim();
- item.content = '';
- }
- }
-
- // 非 Agent 模式下若 content 为空(例如用户停止时尚未产出任何文字),
- // 保持为空;botmsg.vue 会因 hasActualContent=false 不渲染内容区和 toolbar。
- // 此前这里会兜底为 "chat.cannotAnswer",会让停止场景显示误导性文案并出现复制按钮。
- processed.push(item);
- }
- if (processed.length > 0) {
- if (isScrollType) {
- // 逆序逐个 unshift,才能保持 user → assistant 的对话顺序。
- for (let i = processed.length - 1; i >= 0; i--) {
- messagesList.unshift(processed[i]);
- }
- } else {
- messagesList.push(...processed);
- }
- }
- if (isFirstEnter.value) {
- scrollToBottom(true);
- } else if (isScrollType && scrollContainer.value && typeof newScrollHeight === 'number') {
- nextTick(() => {
- if (!scrollContainer.value) return;
- const { scrollHeight } = scrollContainer.value;
- scrollContainer.value.scrollTop = scrollHeight - newScrollHeight;
- });
- }
- if (messagesList[messagesList.length - 1] && !messagesList[messagesList.length - 1].is_completed) {
- isReplying.value = true;
- // 保存正在 stream 的消息 ID,以便停止时使用
- const lastMessage = messagesList[messagesList.length - 1];
- if (lastMessage.role === 'assistant') {
- currentAssistantMessageId.value = lastMessage.id;
- console.log('[Continue Stream] Set assistant message ID:', lastMessage.id);
- }
- // Only IM-originated replies (channel === 'im') get the quiet poll-to-recover
- // path: their answer is generated on the IM side and never streams through
- // this server, so continue-stream always 404s even though the reply *is*
- // coming. Web/api replies keep the original behaviour (a real failure to
- // resume the stream still surfaces as an error) — we don't touch them.
- isAttachingImStream.value = lastMessage.channel === 'im';
- await startStream({ session_id: session_id.value, query: lastMessage.id, method: 'GET', url: '/api/v1/sessions/continue-stream' });
- // On success the stream resumed normally; on failure the error watcher
- // already took over (quiet recovery for IM), so only clear the flag here.
- if (!error.value) isAttachingImStream.value = false;
- }
-
-}
-const checkmenuTitle = (session_id) => {
- menuArr.value[1].children?.forEach(item => {
- if (item.id == session_id) {
- isNeedTitle.value = item.isNoTitle;
- }
- });
-}
// 发送消息
// 处理停止生成事件 - 立即清除 loading 状态
const handleStopGeneration = () => {
@@ -735,7 +532,6 @@ const handleStopGeneration = () => {
};
const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = [], attachmentFiles = []) => {
- userquery.value = value;
isReplying.value = true;
loading.value = true;
@@ -826,9 +622,8 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
// Get selected agent ID (backend resolves shared agent and its tenant from share relation)
const selectedAgentId = props.embeddedMode ? props.agentId : (useSettingsStoreInstance.selectedAgentId || '');
- // Use agent-chat endpoint when agent is enabled, otherwise use knowledge-chat
const endpoint = agentEnabled ? '/api/v1/agent-chat' : '/api/v1/knowledge-chat';
-
+
// Get selected MCP services from settings store (if available)
const mcpServiceIds = props.embeddedMode ? [] : (useSettingsStoreInstance.settings.selectedMCPServices || []);
@@ -847,7 +642,7 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
attachment_uploads: attachmentUploads.length > 0 ? attachmentUploads : undefined,
query: value,
method: 'POST',
- url: endpoint
+ url: endpoint,
});
}
@@ -917,671 +712,25 @@ watch(error, (newError) => {
currentAssistantMessageId.value = '';
});
-// 处理流式数据
onChunk((data) => {
- // 日志:打印接收到的事件
- console.log('[Agent Event Received]', {
- response_type: data.response_type,
- id: data.id,
- done: data.done,
- content_length: data.content?.length || 0,
- content_preview: data.content ? data.content.substring(0, 50) : '',
- data: data.data,
- session_id: data.session_id,
- assistant_message_id: data.assistant_message_id
- });
-
- // 处理 agent query 事件 - 保存 assistant message ID 并保持 loading 状态
- if (data.response_type === 'agent_query') {
- pendingStreamDebug.value = buildStreamDebugPayload();
- if (data.id) {
- const earlyMsg = findLastMessage((item) => item.role === 'assistant' && !item.is_completed);
- if (earlyMsg) {
- earlyMsg.request_id = data.id;
- attachStreamDebugToMessage(earlyMsg);
- }
- }
- if (data.assistant_message_id) {
- currentAssistantMessageId.value = data.assistant_message_id;
- console.log('[Agent Query] Saved assistant message ID:', data.assistant_message_id);
- }
- console.log('[Agent Query Event]', {
- session_id: data.session_id || data.data?.session_id,
- assistant_message_id: data.assistant_message_id,
- query: data.data?.query,
- request_id: data.data?.request_id
- });
-
- // 检查是否是继续流式传输(消息已存在)
- let existingMessage = findLastMessage((item) => item.id === data.id || item.request_id === data.id);
- if (!existingMessage) {
- // 预建 Agent 占位消息,确保紧随其后的 answer 分片走 handleAgentChunk
- // 写入 agentEventStream,而不是非 Agent 路径的 message.content。
- existingMessage = {
- id: data.id,
- request_id: data.id,
- role: 'assistant',
- content: '',
- isAgentMode: true,
- is_completed: false,
- agentEventStream: [],
- _eventMap: new Map(),
- _pendingToolCalls: new Map(),
- knowledge_references: [],
- };
- messagesList.push(existingMessage);
- attachStreamDebugToMessage(existingMessage);
- // 保持全局 Loading,直到首个 thinking/answer/tool 到达(handleAgentChunk
- // 会关闭)。若此处过早 loading=false,eventStream 仍为空时 Agent 内也无
- // 指示器,会出现「闪一下消失 → 空白 → 再出答案/再 Loading」。
- scrollToBottom(true);
- console.log('[Agent Query] Created agent placeholder message');
- } else {
- ensureAgentMessageShell(existingMessage, data.id);
- console.log('[Agent Query] Continuing stream for existing message');
- }
- return;
- }
-
- // 处理会话标题更新事件 - 不关闭 loading
if (data.response_type === 'session_title') {
const title = data.content || data.data?.title;
if (title && data.data?.session_id) {
console.log('[Session Title Update]', {
session_id: data.data.session_id,
- title: title
+ title: title,
});
usemenuStore.updatasessionTitle(data.data.session_id, title);
usemenuStore.changeIsFirstSession(false);
- isNeedTitle.value = false;
- }
- // 不关闭 loading,等待实际内容
- return;
- }
-
- // 判断是否是 Agent 模式的响应
- // 注意:'answer', 'complete', 'references' 类型可能在两种模式下都存在
- // 只有 'thinking', 'tool_call', 'tool_result', 'reflection' 是 Agent 专有的
- const isAgentOnlyResponse = data.response_type === 'thinking' ||
- data.response_type === 'tool_call' ||
- data.response_type === 'tool_result' ||
- data.response_type === 'reflection';
-
- // 检查当前消息是否已经是 Agent 模式
- const lastMessage = messagesList[messagesList.length - 1];
- const isCurrentlyAgentMode = lastMessage?.isAgentMode === true;
- const targetsActiveAgentRequest =
- isAgentStreamSession() &&
- !!data.id &&
- (data.id === currentAssistantMessageId.value ||
- lastMessage?.request_id === data.id ||
- lastMessage?.id === data.id);
- // Agent 开场白会先以 answer 分片流出;若此时尚未打上 isAgentMode,
- // 会误走非 Agent 路径写入 message.content,tool_call 后才切到 Agent,
- // AgentStreamDisplay 读不到 agentEventStream 中的开场白。
- const isAgentAnswerChunk =
- data.response_type === 'answer' && (isAgentStreamSession() || targetsActiveAgentRequest);
- const isAgentCompleteChunk =
- data.response_type === 'complete' && (isAgentStreamSession() || targetsActiveAgentRequest);
-
- // 如果是 Agent 专有的响应类型,或者当前消息已经是 Agent 模式,则走 Agent 处理
- const shouldHandleAsAgent =
- isAgentOnlyResponse ||
- isCurrentlyAgentMode ||
- isAgentAnswerChunk ||
- isAgentCompleteChunk;
-
- // 处理 references 事件 - 在两种模式下都需要处理,但不改变模式
- if (data.response_type === 'references') {
- // 如果当前是 Agent 模式,走 Agent 处理
- if (isCurrentlyAgentMode) {
- handleAgentChunk(data);
- return;
- }
- // 非 Agent 模式:将 references 保存到消息中供 botmsg 使用
- let existingMessage = findLastMessage((item) => item.request_id === data.id || item.id === data.id);
-
- // 如果消息还不存在,先创建一个空的 assistant 消息
- if (!existingMessage) {
- existingMessage = {
- id: data.id,
- request_id: data.id,
- role: 'assistant',
- content: '',
- showThink: false,
- thinkContent: '',
- thinking: false,
- is_completed: false,
- knowledge_references: []
- };
- messagesList.push(existingMessage);
- attachStreamDebugToMessage(existingMessage);
- loading.value = false; // 消息已创建,关闭 loading
- scrollToBottom(true);
- }
-
- existingMessage.knowledge_references = data.knowledge_references || data.data?.references || [];
- console.log('[References] Saved to message, count:', existingMessage.knowledge_references.length);
- return;
- }
-
- // Agent 模式处理(包括 stop 事件)
- if (shouldHandleAsAgent) {
- // 在 handleAgentChunk 中处理 loading 状态
- handleAgentChunk(data);
-
- // 对于 stop 事件,额外处理全局状态
- if (data.response_type === 'stop') {
- console.log('[Stop Event] Generation stopped');
- loading.value = false;
- isReplying.value = false;
- // 清空当前 assistant message ID
- currentAssistantMessageId.value = '';
- }
- return;
- }
-
- // 原有的知识库 QA 处理逻辑(非 Agent 模式)
- // answer 内容中可能包含 <think>...</think> 标签
-
- // 非 Agent 模式下的 stop 事件:只更新状态,不把后端附带的 "Generation stopped by user"
- // 文案拼进 content,保留用户点停止时已经流式输出的内容不变。
- if (data.response_type === 'stop') {
- console.log('[Stop Event] Non-agent generation stopped');
- const stoppedMessage = findLastMessage((item) => {
- if (item.request_id === data.id) return true;
- return item.id === data.id;
- });
- if (stoppedMessage) {
- stoppedMessage.is_completed = true;
+ window.dispatchEvent(new CustomEvent('session-title-updated', {
+ detail: { sessionId: data.data.session_id, title },
+ }));
}
- loading.value = false;
- isReplying.value = false;
- fullContent.value = '';
- currentAssistantMessageId.value = '';
- return;
- }
-
- // 检查消息是否已经完成,如果已完成则忽略后续的完成事件(防止空内容覆盖)
- const existingMessage = findLastMessage((item) => {
- if (item.request_id === data.id) {
- return true
- }
- return item.id === data.id;
- });
-
- // 如果消息已完成且当前事件是完成事件(done=true 且无内容),直接忽略
- if (existingMessage?.is_completed && data.done && !data.content) {
- console.log('[Non-Agent] Ignoring duplicate completion event for completed message');
return;
}
-
- fullContent.value += data.content;
- let obj = { ...data, content: '', role: 'assistant', showThink: false, is_completed: false };
-
- // 检查是否为 fallback 回答(未从知识库检索到内容)
- if (data.data?.is_fallback) {
- obj.is_fallback = true;
- }
-
- const thinkCloseTag = '</think>';
- if (fullContent.value.includes('<think>') && !fullContent.value.includes(thinkCloseTag)) {
- obj.thinking = true;
- obj.showThink = true;
- obj.content = '';
- obj.thinkContent = fullContent.value.replace('<think>', '').trim();
- } else if (fullContent.value.includes('<think>') && fullContent.value.includes(thinkCloseTag)) {
- obj.thinking = false;
- obj.showThink = true;
- // Use lastIndexOf to handle edge cases with multiple </think> occurrences,
- // consistent with history loading logic (line 280)
- const index = fullContent.value.lastIndexOf(thinkCloseTag);
- obj.thinkContent = fullContent.value.substring(0, index).replace('<think>', '').trim();
- obj.content = fullContent.value.substring(index + thinkCloseTag.length).trim();
- } else {
- obj.content = fullContent.value;
- }
-
- if (!existingMessage) {
- loading.value = false; // 消息即将创建,关闭 loading
- }
-
- if (data.done) {
- // 标记消息已完成
- obj.is_completed = true;
- // 标题生成已改为异步事件推送,不再需要在这里手动调用
- // 如果标题还未生成,前端会通过 SSE 事件接收
- isReplying.value = false;
- fullContent.value = "";
- // 清空当前 assistant message ID
- currentAssistantMessageId.value = '';
- }
- updateAssistantSession(obj);
-})
-// 处理 Agent 流式数据 (Cursor-style UI)
-const handleAgentChunk = (data) => {
- let message = findLastMessage((item) => item.request_id === data.id || item.id === data.id);
-
- if (!message) {
- // 创建新的 Assistant 消息 - 此时开始显示内容,关闭 loading
- const newMsg = {
- id: data.id,
- request_id: data.id,
- role: 'assistant',
- content: '',
- isAgentMode: true,
- // Event stream: ordered list of all agent events (thinking, tool calls, etc)
- agentEventStream: [],
- // Map to track event by event_id for quick lookup
- _eventMap: new Map(),
- knowledge_references: []
- };
- messagesList.push(newMsg);
- attachStreamDebugToMessage(newMsg);
- pendingStreamDebug.value = null;
- loading.value = false; // 消息已创建,关闭 loading
- scrollToBottom(true);
- // Don't return - continue to process the current event data
- message = newMsg;
- } else {
- attachStreamDebugToMessage(message);
- pendingStreamDebug.value = null;
- }
-
- message.isAgentMode = true;
-
- // 确保在继续流式传输时(刷新页面场景),一旦接收到实际内容就关闭 loading
- // 这是一个保护措施,防止任何边缘情况导致 loading 残留
- if (loading.value && (data.response_type === 'thinking' || data.response_type === 'answer' || data.response_type === 'tool_call' || data.response_type === 'tool_approval_required')) {
- console.log('[Agent Chunk] Closing loading for continued stream');
- loading.value = false;
- }
-
- switch(data.response_type) {
- case 'thinking':
- {
- const eventId = data.data?.event_id;
- console.log('[Thinking Event]', {
- event_id: eventId,
- done: data.done,
- content_length: data.content?.length || 0
- });
-
- // Initialize structures
- if (!message.agentEventStream) message.agentEventStream = [];
- if (!message._eventMap) message._eventMap = new Map();
-
- if (!data.done) {
- // Check if this thinking event already exists
- let thinkingEvent = message._eventMap.get(eventId);
-
- if (!thinkingEvent) {
- // Create new thinking event
- console.log('[Thinking] Creating new thinking event, event_id:', eventId);
- thinkingEvent = {
- type: 'thinking',
- event_id: eventId,
- content: '',
- done: false,
- startTime: Date.now(),
- thinking: true
- };
-
- // Add to event stream
- message.agentEventStream.push(thinkingEvent);
- message._eventMap.set(eventId, thinkingEvent);
- }
-
- // Accumulate content
- if (data.content) {
- thinkingEvent.content += data.content;
- console.log('[Thinking] Event', eventId, 'accumulated:', thinkingEvent.content.length, 'chars');
- }
-
- } else {
- // Thinking completed
- const thinkingEvent = message._eventMap.get(eventId);
- if (thinkingEvent) {
- console.log('[Thinking] Completing event, event_id:', eventId, 'content length:', thinkingEvent.content.length);
-
- // Mark as done
- thinkingEvent.done = true;
- thinkingEvent.thinking = false;
- thinkingEvent.duration_ms = data.data?.duration_ms || (Date.now() - thinkingEvent.startTime);
- thinkingEvent.completed_at = data.data?.completed_at || Date.now();
-
- console.log('[Thinking] Event completed, duration:', thinkingEvent.duration_ms, 'ms');
- } else {
- console.warn('[Thinking] Received done for unknown event_id:', eventId);
- }
- }
- }
- break;
-
- case 'tool_approval_required': {
- if (!message.agentEventStream) message.agentEventStream = [];
- const d = data.data || {};
- message.agentEventStream.push({
- type: 'tool_approval_required',
- pending_id: d.pending_id,
- service_name: d.service_name,
- mcp_tool_name: d.mcp_tool_name,
- description: d.description,
- args_json: d.args_json,
- timeout_seconds: d.timeout_seconds,
- requested_at: d.requested_at,
- tool_call_id: d.tool_call_id,
- resolved: false,
- });
- break;
- }
- case 'tool_approval_resolved': {
- const d = data.data || {};
- const pid = d.pending_id;
- const ev = message.agentEventStream?.find(
- (e) => e.type === 'tool_approval_required' && e.pending_id === pid
- );
- if (ev) {
- ev.resolved = true;
- ev.approved = d.approved;
- ev.resolve_reason = d.reason;
- ev.timed_out = d.timed_out;
- ev.canceled = d.canceled;
- }
- break;
- }
- case 'tool_call':
- // Legacy guard: the final_answer tool has been removed, but old
- // streamed/replayed data may still carry it — its content appears
- // as answer events, so skip the tool-call rendering.
- if (data.data && data.data.tool_name === 'final_answer') {
- break;
- }
- // 任何在本工具调用之前流入答案区的纯文本都是这一轮的开场白,而非最终
- // 答案(Agent 只会以"纯文本、无工具调用"自然结束)。因此一旦出现工具
- // 调用,就把先前的答案片段从答案区回撤、交给步骤树重新定位,等效于旧的
- // 后端 superseded 标记,并用剩余片段重组 message.content。
- if (message.agentEventStream) {
- let retracted = false;
- for (const ev of message.agentEventStream) {
- if (ev.type === 'answer' && !ev.superseded && ev.content && ev.content.trim()) {
- ev.superseded = true;
- ev.done = true;
- retracted = true;
- }
- }
- if (retracted) {
- message.content = recomposeAgentAnswer(message);
- fullContent.value = message.content;
- }
- }
- // Store or update pending tool call to pair with result later
- if (data.data && (data.data.tool_name || data.data.tool_call_id)) {
- const incomingToolName = data.data.tool_name;
- const incomingArguments = data.data.arguments;
-
- if (!message.agentEventStream) message.agentEventStream = [];
- if (!message._pendingToolCalls) message._pendingToolCalls = new Map();
-
- const toolCallId = data.data.tool_call_id || (incomingToolName ? (incomingToolName + '_' + Date.now()) : null);
- if (!toolCallId) {
- console.warn('[Tool Call] Received event without identifiable tool_call_id:', data.data);
- break;
- }
-
- console.log('[Tool Call]', {
- tool_call_id: toolCallId,
- tool_name: incomingToolName,
- has_arguments: Boolean(incomingArguments)
- });
-
- let toolCallEvent = message._pendingToolCalls.get(toolCallId);
- if (!toolCallEvent) {
- toolCallEvent = message.agentEventStream.find(
- (event) => event.type === 'tool_call' && event.tool_call_id === toolCallId
- );
- }
-
- if (toolCallEvent) {
- if (incomingToolName) toolCallEvent.tool_name = incomingToolName;
- if (incomingArguments) toolCallEvent.arguments = incomingArguments;
- toolCallEvent.pending = true;
- if (!toolCallEvent.timestamp) {
- toolCallEvent.timestamp = Date.now();
- }
- message._pendingToolCalls.set(toolCallId, toolCallEvent);
- } else {
- const newToolCallEvent = {
- type: 'tool_call',
- tool_call_id: toolCallId,
- tool_name: incomingToolName,
- arguments: incomingArguments,
- timestamp: Date.now(),
- pending: true
- };
- message.agentEventStream.push(newToolCallEvent);
- message._pendingToolCalls.set(toolCallId, newToolCallEvent);
- }
- }
- break;
-
- case 'tool_result':
- case 'error':
- // Tool result - update the corresponding tool call event
- if (data.data) {
- const toolCallId = data.data.tool_call_id;
- const toolName = data.data.tool_name;
- const success = data.response_type !== 'error' && data.data.success !== false;
-
- console.log('[Tool Result]', {
- tool_call_id: toolCallId,
- tool_name: toolName,
- success: success
- });
-
- // Find and update the pending tool call event
- let toolCallEvent = null;
- if (message._pendingToolCalls) {
- if (toolCallId && message._pendingToolCalls.has(toolCallId)) {
- toolCallEvent = message._pendingToolCalls.get(toolCallId);
- message._pendingToolCalls.delete(toolCallId);
- } else {
- // Try to find by tool_name if no tool_call_id match
- for (const [key, value] of message._pendingToolCalls.entries()) {
- if (value.tool_name === toolName) {
- toolCallEvent = value;
- message._pendingToolCalls.delete(key);
- break;
- }
- }
- }
- }
-
- if (toolCallEvent) {
- // Update the existing event with result
- toolCallEvent.pending = false;
- toolCallEvent.success = success;
- toolCallEvent.output = success ? (data.data.output || data.content) : (data.data.error || data.content);
- toolCallEvent.error = !success ? (data.data.error || data.content) : undefined;
- // Set both duration and duration_ms for compatibility
- const duration = data.data.duration_ms !== undefined ? data.data.duration_ms : data.data.duration;
- toolCallEvent.duration = duration;
- toolCallEvent.duration_ms = duration;
- toolCallEvent.display_type = data.data.display_type;
- toolCallEvent.tool_data = data.data;
-
- console.log('[Tool Result] Updated event in stream');
- } else {
- console.warn('[Tool Result] No pending tool call found for', toolCallId || toolName);
- }
-
- // If this is an error response without tool data, handle it
- if (data.response_type === 'error' && !toolName) {
- const errorMsg = data.content || t('chat.processError');
- message.content = errorMsg;
- message.is_completed = true;
- isReplying.value = false;
- loading.value = false;
- MessagePlugin.error(errorMsg);
- console.error('[Chat Error]', errorMsg);
- }
- } else if (data.response_type === 'error') {
- // Generic error without tool context
- const errorMsg = data.content || t('chat.processError');
- message.content = errorMsg;
- message.is_completed = true;
- isReplying.value = false;
- loading.value = false;
- MessagePlugin.error(errorMsg);
- console.error('[Chat Error]', errorMsg);
- }
- break;
-
-
- case 'references':
- // 知识引用
- if (data.data?.references) {
- message.knowledge_references = data.data.references;
- } else if (data.knowledge_references) {
- // 兼容旧格式
- message.knowledge_references = data.knowledge_references;
- }
- break;
-
- case 'answer': {
- // 最终答案(乐观流式)。普通 content 先按答案样式流入答案区;若这一轮
- // 其实调用了工具(是开场白),后续的 tool_call 事件会把该片段从答案区
- // 回撤、交给步骤树重新定位(见 'tool_call' 分支),并用剩余未被回撤的
- // 片段重组 message.content。每轮答案各自一个事件(按 event_id 区分),
- // 这样开场白不会和最终答案合并。
- message.thinking = false;
- const eventId = data.data?.event_id;
- if (!message.agentEventStream) message.agentEventStream = [];
- if (!message._eventMap) message._eventMap = new Map();
-
- let answerEvent = eventId
- ? message._eventMap.get(eventId)
- : message.agentEventStream.find((e) => e.type === 'answer' && !e.event_id);
- if (!answerEvent) {
- answerEvent = { type: 'answer', event_id: eventId, content: '', done: false };
- message.agentEventStream.push(answerEvent);
- if (eventId) message._eventMap.set(eventId, answerEvent);
- }
-
- // 若 answer 分片曾误走非 Agent 路径,首次进入 Agent 处理时迁入事件流
- if (!answerEvent.content && message.content && message.content.trim()) {
- answerEvent.content = message.content;
- }
-
- // 只有当有实际内容时才追加,避免空内容覆盖
- if (data.content) {
- answerEvent.content += data.content;
- message.content = recomposeAgentAnswer(message);
- fullContent.value = message.content;
- }
-
- // 检查是否为 fallback 回答
- if (data.data?.is_fallback) {
- answerEvent.is_fallback = true;
- message.is_fallback = true;
- }
-
- // 只在第一次收到 done:true 时标记完成,忽略后续重复的完成事件
- if (data.done && !answerEvent.done) {
- answerEvent.done = true;
- attachStreamDebugToMessage(message);
- pendingStreamDebug.value = null;
-
- // 完成 - 关闭所有状态
- loading.value = false;
- isReplying.value = false;
- fullContent.value = '';
- // 清空当前 assistant message ID
- currentAssistantMessageId.value = '';
- }
- break;
- }
-
- case 'complete':
- // 整个流式响应完成事件 - 确保状态正确关闭
- console.log('[Agent] Complete event received');
- loading.value = false;
- isReplying.value = false;
- message.is_completed = true;
- fullContent.value = '';
- currentAssistantMessageId.value = '';
- // 将 total_duration_ms 存入事件流供 AgentStreamDisplay 使用
- if (message.agentEventStream) {
- message.agentEventStream.push({
- type: 'agent_complete',
- total_duration_ms: data.data?.total_duration_ms || 0,
- total_steps: data.data?.total_steps || 0,
- });
- }
- break;
-
- case 'stop':
- // 停止事件 - 添加到事件流并标记对话完成
- console.log('[Agent] Stop event received');
- if (!message.agentEventStream) message.agentEventStream = [];
-
- // Add stop event to stream
- message.agentEventStream.push({
- type: 'stop',
- timestamp: Date.now(),
- reason: data.data?.reason || 'user_requested'
- });
-
- // Mark conversation as stopped
- isReplying.value = false;
- fullContent.value = '';
- break;
- }
-
- scrollToBottom();
-};
+ processStreamChunk(data);
+});
-const updateAssistantSession = (payload) => {
- const message = findLastMessage((item) => {
- if (item.request_id === payload.id) {
- return true
- }
- return item.id === payload.id;
- });
- if (message) {
- if (payload.id && !message.request_id) {
- message.request_id = payload.id;
- }
- message.content = payload.content;
- message.thinking = payload.thinking;
- message.thinkContent = payload.thinkContent;
- message.showThink = payload.showThink;
- message.knowledge_references = message.knowledge_references ? message.knowledge_references : payload.knowledge_references;
- // 更新 fallback 状态
- if (payload.is_fallback) {
- message.is_fallback = true;
- }
- // 更新完成状态
- if (payload.is_completed) {
- message.is_completed = true;
- }
- attachStreamDebugToMessage(message);
- if (payload.is_completed) {
- pendingStreamDebug.value = null;
- }
- } else {
- const entry = { ...payload };
- if (entry.id && !entry.request_id) {
- entry.request_id = entry.id;
- }
- messagesList.push(entry);
- attachStreamDebugToMessage(entry);
- if (payload.is_completed) {
- pendingStreamDebug.value = null;
- }
- }
- scrollToBottom();
-}
const handleSessionCleared = (e) => {
if (e.detail?.sessionId === session_id.value) {
messagesList.splice(0);
@@ -1594,7 +743,7 @@ const handleSessionCleared = (e) => {
onBeforeMount(async () => {
// 若从智能体列表点击共享智能体进入,URL 带 agent_id 与 source_tenant_id,同步到 store
- const agentIdFromQuery = props.embeddedAgentId || (route.query.agent_id && String(route.query.agent_id));
+ const agentIdFromQuery = props.agentId || (route.query.agent_id && String(route.query.agent_id));
const sourceTenantIdFromQuery = route.query.source_tenant_id && String(route.query.source_tenant_id);
if (agentIdFromQuery && sourceTenantIdFromQuery) {
useSettingsStoreInstance.selectAgent(agentIdFromQuery, sourceTenantIdFromQuery);
@@ -1602,8 +751,8 @@ onBeforeMount(async () => {
useSettingsStoreInstance.selectAgent(agentIdFromQuery, null);
}
- if (props.embeddedKbIds && props.embeddedKbIds.length > 0) {
- useSettingsStoreInstance.selectKnowledgeBases(props.embeddedKbIds);
+ if (props.kbIds && props.kbIds.length > 0) {
+ useSettingsStoreInstance.selectKnowledgeBases(props.kbIds);
}
// 必须在 Input-field onMounted 之前完成:按 session.last_request_state 恢复输入栏
@@ -1618,7 +767,6 @@ onMounted(async () => {
loading.value = false;
isReplying.value = false;
- checkmenuTitle(session_id.value)
if (firstQuery.value) {
scrollLock.value = true;
historyLoading.value = false;
@@ -1647,11 +795,9 @@ const clearData = () => {
stopStream();
isReplying.value = false;
fullContent.value = '';
- userquery.value = '';
// Stop any IM-reply recovery poll for the session we're leaving/switching.
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
isImRecovering.value = false;
-
}
onUnmounted(() => {
window.removeEventListener('session-messages-cleared', handleSessionCleared);
@@ -1701,14 +847,20 @@ onBeforeRouteUpdate((to, from, next) => {
}
&.is-embedded :deep(.answers-input) {
+ position: relative;
transform: translateX(0);
width: 100%;
left: 0;
+ bottom: auto;
display: flex;
justify-content: center;
}
- :deep(.answers-input) {
+ &.is-embedded :deep(.control-bar) {
+ justify-content: flex-end;
+ }
+
+ &:not(.is-embedded) :deep(.answers-input) {
position: static;
transform: translateX(0);
@@ -1716,6 +868,12 @@ onBeforeRouteUpdate((to, from, next) => {
width: 100% !important;
}
}
+
+ &.is-embedded :deep(.answers-input) .t-textarea__inner {
+ width: 100% !important;
+ min-height: 48px !important;
+ padding: 10px 14px 48px 14px;
+ }
}
.chat_scroll_box {
@@ -1788,30 +946,6 @@ onBeforeRouteUpdate((to, from, next) => {
transform: translateX(-50%) translateY(8px);
}
-.agent-mode-indicator {
- display: flex;
- align-items: center;
- gap: 8px;
- padding: 8px 16px;
- background: var(--td-brand-color-light);
- border: 1px solid var(--td-brand-color-focus);
- border-radius: 6px;
- margin-bottom: 12px;
- max-width: 800px;
- width: 100%;
-
- .agent-icon {
- font-size: 20px;
- }
-
- .agent-text {
- font-size: 14px;
- font-weight: 500;
- color: var(--td-brand-color);
- flex: 1;
- }
-}
-
@keyframes contentFadeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
@@ -1851,6 +985,9 @@ onBeforeRouteUpdate((to, from, next) => {
max-width: 100%;
width: 100%;
margin: 0;
+ padding: 12px 16px 16px;
+ min-height: auto;
+ box-sizing: border-box;
overflow-x: hidden;
}
}
diff --git a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
index 1e5bc6c69..d96d1bdeb 100644
--- a/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
+++ b/frontend/src/views/knowledge/KnowledgeBaseEditorModal.vue
@@ -17,17 +17,20 @@
<h2 class="sidebar-title">{{ mode === 'create' ? $t('knowledgeEditor.titleCreate') : $t('knowledgeEditor.titleEdit') }}</h2>
</div>
<div class="settings-nav" data-guide="kb-editor-sidebar">
- <div
- v-for="(item, index) in navItems"
- :key="index"
- :class="['nav-item', { 'active': currentSection === item.key }]"
- :data-guide="`kb-editor-nav-${item.key}`"
- @click="currentSection = item.key"
- >
- <t-icon :name="item.icon" class="nav-icon" />
- <span class="nav-label">{{ item.label }}</span>
- <span v-if="item.badge" class="nav-badge">{{ item.badge }}</span>
- </div>
+ <template v-for="group in navGroups" :key="group.key">
+ <div class="nav-group-title">{{ group.label }}</div>
+ <div
+ v-for="(item, index) in group.items"
+ :key="index"
+ :class="['nav-item', { 'active': currentSection === item.key }]"
+ :data-guide="`kb-editor-nav-${item.key}`"
+ @click="currentSection = item.key"
+ >
+ <t-icon :name="item.icon" class="nav-icon" />
+ <span class="nav-label">{{ item.label }}</span>
+ <span v-if="item.badge" class="nav-badge">{{ item.badge }}</span>
+ </div>
+ </template>
</div>
</div>
@@ -549,6 +552,35 @@ const navItems = computed(() => {
return items
})
+// 左侧导航分组(与 AgentEditorModal 对齐)
+const navGroups = computed(() => {
+ const itemMap = new Map(navItems.value.map((item) => [item.key, item]))
+ const pickItems = (keys: string[]) =>
+ keys.map((key) => itemMap.get(key)).filter(Boolean) as typeof navItems.value
+ return [
+ {
+ key: 'basic',
+ label: t('knowledgeEditor.navGroups.basic'),
+ items: pickItems(['basic', 'models', 'vectorStore', 'faq']),
+ },
+ {
+ key: 'processing',
+ label: t('knowledgeEditor.navGroups.processing'),
+ items: pickItems(['parser', 'chunking', 'multimodal', 'asr', 'graph', 'advanced']),
+ },
+ {
+ key: 'data',
+ label: t('knowledgeEditor.navGroups.data'),
+ items: pickItems(['storage', 'datasource']),
+ },
+ {
+ key: 'integration',
+ label: t('knowledgeEditor.navGroups.integration'),
+ items: pickItems(['share']),
+ },
+ ].filter((group) => group.items.length > 0)
+})
+
// 模型配置引用
const modelConfigRef = ref<InstanceType<typeof KBModelConfig>>()
const advancedSettingsRef = ref<InstanceType<typeof KBAdvancedSettings>>()
@@ -1442,68 +1474,89 @@ watch(
.settings-container {
display: flex;
height: 100%;
+ width: 100%;
overflow: hidden;
}
+/* 左侧导航:与 AgentEditorModal 对齐 */
.settings-sidebar {
- width: 200px;
- background: var(--td-bg-color-settings-modal);
+ width: 208px;
+ background-color: var(--td-bg-color-settings-modal);
border-right: 1px solid var(--td-component-stroke);
+ flex-shrink: 0;
display: flex;
flex-direction: column;
- flex-shrink: 0;
+ overflow: hidden;
}
.sidebar-header {
- padding: 24px 20px;
+ padding: 16px 14px 12px;
border-bottom: 1px solid var(--td-component-stroke);
+ flex-shrink: 0;
}
.sidebar-title {
margin: 0;
- font-family: var(--app-font-family);
- font-size: 18px;
+ font-size: 16px;
font-weight: 600;
color: var(--td-text-color-primary);
}
.settings-nav {
flex: 1;
- padding: 12px 8px;
+ padding: 8px 8px 12px;
overflow-y: auto;
+ min-height: 0;
+}
+
+.nav-group-title {
+ padding: 6px 14px 2px;
+ color: var(--td-text-color-placeholder);
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+
+ .settings-nav > &:first-child {
+ padding-top: 2px;
+ }
+
+ .settings-nav > &:not(:first-child) {
+ padding-top: 8px;
+ }
}
.nav-item {
display: flex;
align-items: center;
- padding: 10px 12px;
- margin-bottom: 4px;
+ padding: 6px 12px;
+ margin-bottom: 2px;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
- font-family: var(--app-font-family);
font-size: 14px;
- color: var(--td-text-color-secondary);
+ color: var(--td-text-color-primary);
+ user-select: none;
&:hover {
- background: var(--td-bg-color-secondarycontainer-hover);
+ background-color: var(--td-bg-color-secondarycontainer-hover);
color: var(--td-text-color-primary);
}
&.active {
- background: var(--td-brand-color-light);
+ background-color: rgba(7, 192, 95, 0.1);
color: var(--td-brand-color);
font-weight: 500;
}
}
.nav-icon {
- margin-right: 8px;
- font-size: 18px;
+ margin-right: 9px;
+ font-size: 16px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
+ color: inherit;
}
.nav-label {
@@ -1511,24 +1564,21 @@ watch(
}
.nav-badge {
- display: inline-flex;
- align-items: center;
- justify-content: center;
+ flex-shrink: 0;
min-width: 18px;
- height: 18px;
- padding: 0 5px;
- border-radius: 9px;
+ padding: 0 6px;
+ border-radius: 10px;
+ background: var(--td-bg-color-secondarycontainer);
font-size: 11px;
font-weight: 600;
- background: var(--td-bg-color-component);
+ line-height: 18px;
+ text-align: center;
color: var(--td-text-color-secondary);
- line-height: 1;
- flex-shrink: 0;
-}
-.nav-item.active .nav-badge {
- background: var(--td-brand-color);
- color: #fff;
+ .nav-item.active & {
+ background: color-mix(in srgb, var(--td-brand-color) 18%, transparent);
+ color: var(--td-brand-color);
+ }
}
.settings-content {
@@ -1554,11 +1604,11 @@ watch(
.section-content {
.section-header {
- margin-bottom: 20px;
+ margin-bottom: 16px;
}
.section-title {
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
font-family: var(--app-font-family);
font-size: 20px;
font-weight: 600;
@@ -1781,13 +1831,13 @@ watch(
width: 100%;
.section-header {
- margin-bottom: 32px;
+ margin-bottom: 20px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -1807,7 +1857,7 @@ watch(
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
diff --git a/frontend/src/views/knowledge/settings/DataSourceSettings.vue b/frontend/src/views/knowledge/settings/DataSourceSettings.vue
index c8d0225bf..9ecc247db 100644
--- a/frontend/src/views/knowledge/settings/DataSourceSettings.vue
+++ b/frontend/src/views/knowledge/settings/DataSourceSettings.vue
@@ -216,129 +216,146 @@ onBeforeUnmount(stopPolling)
<p class="section-desc">{{ t('datasource.description') }}</p>
</div>
- <div v-if="loading" class="ds-loading">
- <t-loading size="small" />
- </div>
-
- <div v-else-if="dataSources.length === 0" class="ds-empty">
- <div class="ds-empty-icon">
- <t-icon name="cloud-download" size="32px" />
+ <div class="channels-section">
+ <div class="channels-header">
+ <span class="channels-title">{{ t('datasource.channelsTitle') }}</span>
+ <span class="channels-count">{{ dataSources.length }}</span>
</div>
- <div class="ds-empty-text">
- <p class="ds-empty-title">{{ t('datasource.empty') }}</p>
- </div>
- <t-button v-if="canManageDataSource" theme="primary" variant="outline" @click="openCreate">
- <template #icon><t-icon name="add" /></template>
- {{ t('datasource.addFirst') }}
- </t-button>
- </div>
- <div v-else class="ds-list">
- <div v-for="ds in dataSources" :key="ds.id" class="ds-card">
- <div class="ds-card-header">
- <div class="ds-card-title-wrap">
- <DataSourceTypeIcon :type="ds.type" :size="32" />
- <div class="ds-title-text">
- <div class="ds-name-row">
- <span class="ds-name" :title="ds.name">{{ ds.name }}</span>
- <t-tag size="small" :theme="statusTheme(ds.status)" variant="light-outline" class="ds-status-tag">
+ <t-loading :loading="loading" size="small" class="channels-loading-wrap">
+ <div
+ v-if="!loading && dataSources.length === 0 && !canManageDataSource"
+ class="channels-empty"
+ >
+ <t-empty :description="t('datasource.empty')" />
+ </div>
+
+ <div v-else-if="!loading" class="channel-grid">
+ <component
+ :is="canManageDataSource ? 'button' : 'div'"
+ v-for="ds in dataSources"
+ :key="ds.id"
+ :type="canManageDataSource ? 'button' : undefined"
+ :class="['channel-card', { 'channel-card--clickable': canManageDataSource }]"
+ @click="canManageDataSource ? openEdit(ds) : undefined"
+ >
+ <div class="channel-card__badge">
+ <DataSourceTypeIcon :type="ds.type" :size="22" />
+ </div>
+ <div class="channel-card__body">
+ <div class="channel-card__header">
+ <h3 class="channel-card__title" :title="ds.name">{{ ds.name }}</h3>
+ <t-tag size="small" :theme="statusTheme(ds.status)" variant="light">
{{ statusLabel(ds.status) }}
</t-tag>
</div>
- <span class="ds-type-desc">{{ connectorLabel(ds.type) }}</span>
+ <p class="channel-card__subtitle">
+ {{ connectorLabel(ds.type) }} · {{ syncModeLabel(ds.sync_mode) }}
+ </p>
+ <div class="channel-card__meta">
+ <div class="channel-card__meta-item">
+ <span class="channel-card__meta-label">{{ t('datasource.schedule') }}</span>
+ <span class="channel-card__meta-value">{{ scheduleLabel(ds.sync_schedule) }}</span>
+ </div>
+ <div class="channel-card__meta-item">
+ <span class="channel-card__meta-label">{{ t('datasource.lastSync') }}</span>
+ <t-tooltip :content="lastSyncFullTime(ds)" :disabled="!lastSyncFullTime(ds)">
+ <span class="channel-card__meta-value">{{ lastSyncTime(ds) }}</span>
+ </t-tooltip>
+ </div>
+ <div class="channel-card__meta-item channel-card__meta-item--wide">
+ <span class="channel-card__meta-label">{{ t('datasource.lastStatus') }}</span>
+ <span class="channel-card__meta-value">
+ <template v-if="ds.latest_sync_log">
+ <span :style="{ color: lastSyncStatusColor(ds), fontWeight: 500 }">
+ {{ lastSyncStatusLabel(ds) }}
+ </span>
+ <span
+ v-for="pill in syncResultPills(ds)"
+ :key="pill.cls"
+ :class="['ds-pill', pill.cls]"
+ >{{ pill.text }}</span>
+ </template>
+ <span v-else class="channel-card__meta-placeholder">--</span>
+ </span>
+ </div>
+ </div>
+ <div v-if="ds.error_message" class="channel-card__error">
+ <t-icon name="error-circle-filled" size="14px" />
+ <span>{{ ds.error_message }}</span>
+ </div>
</div>
- </div>
-
- <div class="ds-card-actions">
- <t-tooltip v-if="canManageDataSource" :content="isSyncRunning(ds) ? t('datasource.logStatus.running') : t('datasource.syncNow')">
- <t-button
- size="small"
- variant="text"
- theme="primary"
- :disabled="isSyncRunning(ds)"
- @click="handleSync(ds)"
+ <div class="channel-card__actions" @click.stop>
+ <t-tooltip
+ v-if="canManageDataSource"
+ :content="isSyncRunning(ds) ? t('datasource.logStatus.running') : t('datasource.syncNow')"
>
- <template #icon>
- <t-icon name="refresh" :class="{ 'ds-icon-spin': isSyncRunning(ds) }" />
- </template>
- </t-button>
- </t-tooltip>
- <t-tooltip :content="t('datasource.logs')">
- <t-button size="small" variant="text" @click="openLogs(ds)">
- <template #icon><t-icon name="root-list" /></template>
- </t-button>
- </t-tooltip>
- <t-dropdown v-if="canManageDataSource" trigger="click" :min-column-width="120">
- <t-tooltip :content="t('datasource.moreActions')">
- <t-button size="small" variant="text" shape="square">
- <template #icon><t-icon name="ellipsis" /></template>
+ <t-button
+ size="small"
+ variant="text"
+ theme="primary"
+ :disabled="isSyncRunning(ds)"
+ @click="handleSync(ds)"
+ >
+ <template #icon>
+ <t-icon name="refresh" :class="{ 'ds-icon-spin': isSyncRunning(ds) }" />
+ </template>
</t-button>
</t-tooltip>
- <template #dropdown>
- <t-dropdown-menu>
- <t-dropdown-item @click="openEdit(ds)">
- <t-icon name="edit" /> {{ t('datasource.edit') }}
- </t-dropdown-item>
- <t-dropdown-item
- v-if="ds.status === 'active'"
- @click="handlePause(ds)"
- >
- <t-icon name="pause-circle" /> {{ t('datasource.pause') }}
- </t-dropdown-item>
- <t-dropdown-item
- v-else-if="ds.status === 'paused'"
- @click="handleResume(ds)"
- >
- <t-icon name="play-circle" /> {{ t('datasource.resume') }}
- </t-dropdown-item>
- <t-dropdown-item theme="error" @click="handleDelete(ds)">
- <t-icon name="delete" /> {{ t('datasource.delete') }}
- </t-dropdown-item>
- </t-dropdown-menu>
- </template>
- </t-dropdown>
- </div>
- </div>
-
- <div class="ds-card-stats">
- <div class="ds-stat-item">
- <span class="ds-stat-label">{{ t('datasource.syncModeLabel') }}</span>
- <span class="ds-stat-value">{{ syncModeLabel(ds.sync_mode) }}</span>
- </div>
- <div class="ds-stat-item">
- <span class="ds-stat-label">{{ t('datasource.schedule') }}</span>
- <span class="ds-stat-value">{{ scheduleLabel(ds.sync_schedule) }}</span>
- </div>
- <div class="ds-stat-item">
- <span class="ds-stat-label">{{ t('datasource.lastSync') }}</span>
- <t-tooltip :content="lastSyncFullTime(ds)" :disabled="!lastSyncFullTime(ds)">
- <span class="ds-stat-value">{{ lastSyncTime(ds) }}</span>
- </t-tooltip>
- </div>
- <div class="ds-stat-item" style="flex: 1.2">
- <span class="ds-stat-label">{{ t('datasource.lastStatus') }}</span>
- <div class="ds-stat-value">
- <template v-if="ds.latest_sync_log">
- <span :style="{ color: lastSyncStatusColor(ds), fontWeight: 500 }">{{ lastSyncStatusLabel(ds) }}</span>
- <span v-for="pill in syncResultPills(ds)" :key="pill.cls" :class="['ds-pill', pill.cls]">{{ pill.text }}</span>
- </template>
- <span v-else class="ds-stat-placeholder">--</span>
+ <t-tooltip :content="t('datasource.logs')">
+ <t-button size="small" variant="text" @click="openLogs(ds)">
+ <template #icon><t-icon name="root-list" /></template>
+ </t-button>
+ </t-tooltip>
+ <t-dropdown v-if="canManageDataSource" trigger="click" :min-column-width="120">
+ <t-button
+ variant="text"
+ shape="square"
+ size="small"
+ class="channel-card__more"
+ @click.stop
+ >
+ <template #icon><t-icon name="ellipsis" /></template>
+ </t-button>
+ <template #dropdown>
+ <t-dropdown-menu>
+ <t-dropdown-item @click="openEdit(ds)">
+ <t-icon name="edit" /> {{ t('datasource.edit') }}
+ </t-dropdown-item>
+ <t-dropdown-item
+ v-if="ds.status === 'active'"
+ @click="handlePause(ds)"
+ >
+ <t-icon name="pause-circle" /> {{ t('datasource.pause') }}
+ </t-dropdown-item>
+ <t-dropdown-item
+ v-else-if="ds.status === 'paused'"
+ @click="handleResume(ds)"
+ >
+ <t-icon name="play-circle" /> {{ t('datasource.resume') }}
+ </t-dropdown-item>
+ <t-dropdown-item theme="error" @click="handleDelete(ds)">
+ <t-icon name="delete" /> {{ t('datasource.delete') }}
+ </t-dropdown-item>
+ </t-dropdown-menu>
+ </template>
+ </t-dropdown>
</div>
- </div>
- </div>
-
- <div v-if="ds.error_message" class="ds-card-error">
- <t-icon name="error-circle-filled" size="16px" />
- <span>{{ ds.error_message }}</span>
+ </component>
+
+ <button
+ v-if="canManageDataSource"
+ type="button"
+ class="channel-card channel-card--add"
+ @click="openCreate"
+ >
+ <span class="channel-card--add__icon" aria-hidden="true">
+ <t-icon name="add" />
+ </span>
+ <span class="channel-card--add__label">{{ t('datasource.add') }}</span>
+ </button>
</div>
- </div>
-
- <div v-if="canManageDataSource" class="ds-card-add" @click="openCreate">
- <div class="ds-card-add-icon">
- <t-icon name="add" size="20px" />
- </div>
- <span>{{ t('datasource.addCard') }}</span>
- </div>
+ </t-loading>
</div>
<DataSourceEditorDialog
@@ -356,218 +373,278 @@ onBeforeUnmount(stopPolling)
</div>
</template>
-<style scoped>
+<style scoped lang="less">
.ds-settings {
- padding: 0;
+ width: 100%;
}
-/* --- Section header --- */
.section-header {
margin-bottom: 20px;
-}
-.section-title {
- margin: 0 0 6px 0;
- font-size: 20px;
- font-weight: 600;
- color: var(--td-text-color-primary);
- letter-spacing: -0.01em;
-}
+ .section-title {
+ margin: 0 0 6px;
+ font-size: 20px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ }
-.section-desc {
- margin: 0;
- font-size: 13px;
- color: var(--td-text-color-placeholder);
- line-height: 20px;
+ .section-desc {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+ }
}
-/* --- Loading --- */
-.ds-loading {
+.channels-header {
display: flex;
align-items: center;
- justify-content: center;
- padding: 60px 0;
-}
+ gap: 8px;
+ margin-bottom: 12px;
-/* --- Empty state --- */
-.ds-empty {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: 56px 24px;
- gap: 16px;
- border: 1px dashed var(--td-border-level-2-color);
- border-radius: 12px;
- background: var(--td-bg-color-container);
-}
+ .channels-title {
+ font-size: 14px;
+ font-weight: 500;
+ color: var(--td-text-color-primary);
+ }
-.ds-empty-icon {
- width: 56px;
- height: 56px;
- display: flex;
- align-items: center;
- justify-content: center;
- border-radius: 14px;
- background: var(--td-brand-color-light);
- color: var(--td-brand-color);
+ .channels-count {
+ padding: 2px 8px;
+ background: var(--td-bg-color-secondarycontainer);
+ border-radius: 10px;
+ font-size: 12px;
+ color: var(--td-text-color-disabled);
+ }
}
-.ds-empty-text {
- text-align: center;
+.channels-loading-wrap {
+ min-height: 80px;
}
-.ds-empty-title {
- margin: 0;
- font-size: 14px;
- color: var(--td-text-color-secondary);
- line-height: 22px;
+.channels-empty {
+ padding: 32px 0;
}
-/* --- List --- */
-.ds-list {
- display: flex;
- flex-direction: column;
- gap: 10px;
+.channel-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 12px;
}
-/* --- Card --- */
-.ds-card {
+.channel-card {
position: relative;
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 14px 16px;
+ border: 1px solid var(--td-component-stroke);
+ border-radius: 10px;
background: var(--td-bg-color-container);
- border: 1px solid var(--td-border-level-2-color);
- border-radius: 8px;
- padding: 15px 20px;
- transition: all 0.2s ease;
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);
-}
+ text-align: left;
+ font: inherit;
+ color: inherit;
+ transition: border-color 0.18s ease, box-shadow 0.18s ease;
+
+ &--clickable {
+ cursor: pointer;
+ width: 100%;
+
+ &:hover,
+ &:focus-visible {
+ border-color: var(--td-brand-color-3, var(--td-brand-color));
+ box-shadow: 0 4px 14px rgba(15, 23, 42, 0.06);
+ outline: none;
+ }
-.ds-card:hover {
- border-color: var(--td-brand-color);
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
-}
+ &:focus-visible {
+ outline: 2px solid var(--td-brand-color);
+ outline-offset: 2px;
+ }
+ }
-/* --- Card header --- */
-.ds-card-header {
- display: flex;
- justify-content: space-between;
- align-items: flex-start;
- margin-bottom: 20px;
-}
+ &--add {
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 68px;
+ border-style: dashed;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ width: 100%;
+
+ &:hover,
+ &:focus-visible {
+ color: var(--td-brand-color);
+ border-color: var(--td-brand-color);
+ background: color-mix(in srgb, var(--td-brand-color) 6%, transparent);
+ box-shadow: none;
+ }
-.ds-card-title-wrap {
- display: flex;
- align-items: center;
- gap: 16px;
- min-width: 0;
- flex: 1;
-}
+ &__icon {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
+ color: var(--td-brand-color);
+ font-size: 18px;
+ }
-.ds-title-text {
- display: flex;
- flex-direction: column;
- gap: 4px;
- min-width: 0;
-}
+ &__label {
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 1.4;
+ }
+ }
-.ds-name-row {
- display: flex;
- align-items: center;
- gap: 8px;
- min-width: 0;
-}
+ &__badge {
+ flex-shrink: 0;
+ width: 36px;
+ height: 36px;
+ border-radius: 9px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--td-brand-color) 10%, transparent);
+ overflow: hidden;
+ }
-.ds-name {
- font-size: 16px;
- font-weight: 600;
- color: var(--td-text-color-primary);
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- line-height: 24px;
-}
+ &__body {
+ flex: 1;
+ min-width: 0;
+ }
-.ds-status-tag {
- border-radius: 4px;
-}
+ &__header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
-.ds-type-desc {
- font-size: 13px;
- color: var(--td-text-color-secondary);
- line-height: 18px;
-}
+ &__title {
+ flex: 1;
+ min-width: 0;
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: var(--td-text-color-primary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
-.ds-card-actions {
- display: flex;
- align-items: center;
- gap: 4px;
- flex-shrink: 0;
- opacity: 0.6;
- transition: opacity 0.2s ease;
-}
+ &__subtitle {
+ margin: 2px 0 0;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--td-text-color-secondary);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
-.ds-card:hover .ds-card-actions {
- opacity: 1;
-}
+ &__meta {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px 12px;
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px solid var(--td-component-stroke);
+ }
-.ds-card-actions :deep(.t-button) {
- border-radius: 6px;
-}
+ &__meta-item {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
-/* --- Info stats --- */
-.ds-card-stats {
- display: flex;
- gap: 24px;
- padding-top: 16px;
- border-top: 1px solid var(--td-border-level-1-color);
-}
+ &--wide {
+ grid-column: 1 / -1;
+ }
+ }
-.ds-stat-item {
- display: flex;
- flex-direction: column;
- gap: 6px;
- flex: 1;
-}
+ &__meta-label {
+ font-size: 11px;
+ line-height: 1.4;
+ color: var(--td-text-color-placeholder);
+ }
-.ds-stat-label {
- font-size: 11px;
- font-weight: 500;
- color: var(--td-text-color-placeholder);
- text-transform: uppercase;
- letter-spacing: 0.5px;
- line-height: 16px;
- white-space: nowrap;
-}
+ &__meta-value {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 4px;
+ font-size: 12px;
+ line-height: 1.4;
+ color: var(--td-text-color-primary);
+ }
-.ds-stat-value {
- display: flex;
- align-items: center;
- gap: 6px;
- flex-wrap: wrap;
- font-size: 13px;
- color: var(--td-text-color-primary);
- line-height: 20px;
-}
+ &__meta-placeholder {
+ color: var(--td-text-color-disabled);
+ }
-.ds-stat-placeholder {
- color: var(--td-text-color-disabled);
+ &__error {
+ display: flex;
+ align-items: flex-start;
+ gap: 6px;
+ margin-top: 8px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ background: var(--td-error-color-1);
+ color: var(--td-error-color);
+ font-size: 12px;
+ line-height: 1.45;
+ text-align: left;
+ }
+
+ &__actions {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding-top: 2px;
+ }
+
+ &__more {
+ flex-shrink: 0;
+ padding: 2px;
+ opacity: 0;
+ color: var(--td-text-color-placeholder);
+ transition: opacity 0.15s ease;
+
+ &:hover,
+ &:focus-visible {
+ background: var(--td-bg-color-secondarycontainer);
+ color: var(--td-text-color-primary);
+ }
+ }
+
+ &:hover .channel-card__more,
+ &:focus-within .channel-card__more,
+ &__actions:focus-within .channel-card__more {
+ opacity: 1;
+ }
}
-/* --- Sync result pills --- */
.ds-pill {
- font-size: 11px;
- padding: 1px 6px;
+ font-size: 10px;
+ padding: 1px 5px;
border-radius: 4px;
font-weight: 500;
font-variant-numeric: tabular-nums;
- line-height: 18px;
-}
+ line-height: 16px;
-.ds-pill.created { background: var(--td-success-color-1); color: var(--td-success-color); }
-.ds-pill.updated { background: var(--td-brand-color-light); color: var(--td-brand-color); }
-.ds-pill.deleted { background: var(--td-warning-color-1); color: var(--td-warning-color); }
-.ds-pill.skipped { background: var(--td-bg-color-component); color: var(--td-text-color-placeholder); }
-.ds-pill.failed { background: var(--td-error-color-1); color: var(--td-error-color); }
+ &.created { background: var(--td-success-color-1); color: var(--td-success-color); }
+ &.updated { background: var(--td-brand-color-light); color: var(--td-brand-color); }
+ &.deleted { background: var(--td-warning-color-1); color: var(--td-warning-color); }
+ &.skipped { background: var(--td-bg-color-component); color: var(--td-text-color-placeholder); }
+ &.failed { background: var(--td-error-color-1); color: var(--td-error-color); }
+}
.ds-icon-spin {
animation: ds-spin 1s linear infinite;
@@ -577,60 +654,4 @@ onBeforeUnmount(stopPolling)
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
-
-/* --- Error alert --- */
-.ds-card-error {
- margin-top: 16px;
- padding: 10px 14px;
- border-radius: 8px;
- background: var(--td-error-color-1);
- color: var(--td-error-color);
- font-size: 13px;
- display: flex;
- align-items: flex-start;
- gap: 8px;
- line-height: 20px;
-}
-
-/* --- Add card --- */
-.ds-card-add {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 12px;
- padding: 6px 15px;
- background: var(--td-bg-color-secondarycontainer);
- border: 1px solid transparent;
- border-radius: 8px;
- color: var(--td-text-color-secondary);
- font-size: 14px;
- font-weight: 500;
- cursor: pointer;
- transition: all 0.2s ease;
- margin-top: 4px;
-}
-
-.ds-card-add-icon {
- display: flex;
- align-items: center;
- justify-content: center;
- width: 32px;
- height: 32px;
- border-radius: 8px;
- background: var(--td-bg-color-component);
- color: var(--td-text-color-placeholder);
- transition: all 0.2s ease;
-}
-
-.ds-card-add:hover {
- background: var(--td-bg-color-container);
- border-color: var(--td-brand-color);
- color: var(--td-brand-color);
- box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
-}
-
-.ds-card-add:hover .ds-card-add-icon {
- background: var(--td-brand-color-light);
- color: var(--td-brand-color);
-}
</style>
diff --git a/frontend/src/views/knowledge/settings/GraphSettings.vue b/frontend/src/views/knowledge/settings/GraphSettings.vue
index 36b17b4a9..8ff2376fe 100644
--- a/frontend/src/views/knowledge/settings/GraphSettings.vue
+++ b/frontend/src/views/knowledge/settings/GraphSettings.vue
@@ -588,13 +588,13 @@ onMounted(async () => {
}
.section-header {
- margin-bottom: 32px;
+ margin-bottom: 20px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -615,7 +615,7 @@ onMounted(async () => {
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
diff --git a/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue b/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue
index c61df634f..67a11766b 100644
--- a/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBAdvancedSettings.vue
@@ -99,13 +99,13 @@ const handleQuestionGenerationChange = () => {
}
.section-header {
- margin-bottom: 32px;
+ margin-bottom: 20px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -126,7 +126,7 @@ const handleQuestionGenerationChange = () => {
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
diff --git a/frontend/src/views/knowledge/settings/KBChunkingSettings.vue b/frontend/src/views/knowledge/settings/KBChunkingSettings.vue
index 38fa77856..1815df572 100644
--- a/frontend/src/views/knowledge/settings/KBChunkingSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBChunkingSettings.vue
@@ -408,8 +408,8 @@ const emitUpdate = () => {
top: -24px;
z-index: 5;
background: var(--td-bg-color-container);
- padding: 24px 32px 16px 32px;
- margin: -24px -32px 24px -32px;
+ padding: 24px 32px 12px 32px;
+ margin: -24px -32px 16px -32px;
border-bottom: 1px solid var(--td-component-stroke);
.section-header-text {
@@ -421,7 +421,7 @@ const emitUpdate = () => {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -442,7 +442,7 @@ const emitUpdate = () => {
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
diff --git a/frontend/src/views/knowledge/settings/KBModelConfig.vue b/frontend/src/views/knowledge/settings/KBModelConfig.vue
index b19726ee1..4207da04e 100644
--- a/frontend/src/views/knowledge/settings/KBModelConfig.vue
+++ b/frontend/src/views/knowledge/settings/KBModelConfig.vue
@@ -138,13 +138,13 @@ const handleAddModel = (subSection: string) => {
}
.section-header {
- margin-bottom: 32px;
+ margin-bottom: 20px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -165,7 +165,7 @@ const handleAddModel = (subSection: string) => {
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
diff --git a/frontend/src/views/knowledge/settings/KBParserSettings.vue b/frontend/src/views/knowledge/settings/KBParserSettings.vue
index 83e86d87f..b4a9fb3ca 100644
--- a/frontend/src/views/knowledge/settings/KBParserSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBParserSettings.vue
@@ -307,13 +307,13 @@ watch(() => props.parserEngineRules, (v) => {
}
.section-header {
- margin-bottom: 32px;
+ margin-bottom: 20px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -346,7 +346,7 @@ watch(() => props.parserEngineRules, (v) => {
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
diff --git a/frontend/src/views/knowledge/settings/KBShareSettings.vue b/frontend/src/views/knowledge/settings/KBShareSettings.vue
index e7c895ebc..e2b46c368 100644
--- a/frontend/src/views/knowledge/settings/KBShareSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBShareSettings.vue
@@ -309,11 +309,11 @@ watch(() => props.kbId, async (newKbId) => {
<style scoped lang="less">
.section-content {
.section-header {
- margin-bottom: 20px;
+ margin-bottom: 16px;
}
.section-title {
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
font-family: var(--app-font-family);
font-size: 20px;
font-weight: 600;
diff --git a/frontend/src/views/knowledge/settings/KBStorageSettings.vue b/frontend/src/views/knowledge/settings/KBStorageSettings.vue
index 1bc1baa23..0486ef855 100644
--- a/frontend/src/views/knowledge/settings/KBStorageSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBStorageSettings.vue
@@ -220,13 +220,13 @@ onMounted(load)
}
.section-header {
- margin-bottom: 32px;
+ margin-bottom: 20px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
- margin: 0 0 8px 0;
+ margin: 0 0 6px 0;
}
.section-description {
@@ -253,7 +253,7 @@ onMounted(load)
display: flex;
align-items: flex-start;
justify-content: space-between;
- padding: 20px 0;
+ padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
}
diff --git a/frontend/src/views/knowledge/settings/KBVectorStoreSettings.vue b/frontend/src/views/knowledge/settings/KBVectorStoreSettings.vue
index 775649f55..f7b1d7594 100644
--- a/frontend/src/views/knowledge/settings/KBVectorStoreSettings.vue
+++ b/frontend/src/views/knowledge/settings/KBVectorStoreSettings.vue
@@ -5,14 +5,14 @@
<p class="section-description">{{ $t('kbSettings.vectorStore.description') }}</p>
</div>
- <!-- CREATE mode: dropdown -->
- <div v-if="props.mode === 'create'" class="settings-group">
- <div v-if="loading" class="loading-inline">
- <t-loading size="small" />
- <span>{{ $t('kbSettings.vectorStore.loading') }}</span>
- </div>
+ <div v-if="props.mode === 'create' && loading" class="loading-inline">
+ <t-loading size="small" />
+ <span>{{ $t('kbSettings.vectorStore.loading') }}</span>
+ </div>
- <div v-else class="setting-row">
+ <!-- CREATE mode: dropdown -->
+ <div v-else-if="props.mode === 'create'" class="settings-group">
+ <div class="setting-row">
<div class="setting-info">
<label>{{ $t('kbSettings.vectorStore.engineLabel') }}</label>
<p class="desc">{{ $t('kbSettings.vectorStore.engineDesc') }}</p>
@@ -23,7 +23,7 @@
size="medium"
:placeholder="$t('kbSettings.vectorStore.systemDefault')"
:clearable="true"
- style="width: 100%; min-width: 240px;"
+ style="width: 100%; min-width: 220px;"
@change="handleChange"
>
<t-option :value="''" :label="$t('kbSettings.vectorStore.systemDefault')">
@@ -177,92 +177,110 @@ onMounted(async () => {
})
</script>
-<style scoped>
+<style lang="less" scoped>
.kb-vector-store-settings {
- display: flex;
- flex-direction: column;
- gap: 16px;
+ width: 100%;
}
-.section-header h2 {
- font-size: 16px;
- font-weight: 600;
- margin: 0 0 4px;
+.section-header {
+ margin-bottom: 20px;
+
+ h2 {
+ font-size: 20px;
+ font-weight: 600;
+ color: var(--td-text-color-primary);
+ margin: 0 0 6px 0;
+ }
+
+ .section-description {
+ font-size: 14px;
+ color: var(--td-text-color-secondary);
+ margin: 0;
+ line-height: 1.5;
+ }
}
-.section-description {
- color: var(--td-text-color-secondary, #4e5969);
+.loading-inline {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 16px 0;
font-size: 13px;
- margin: 0;
+ color: var(--td-text-color-secondary);
}
.settings-group {
- background: var(--td-bg-color-container, #fff);
- border: 1px solid var(--td-component-stroke, #dcdcdc);
- border-radius: 6px;
- padding: 16px;
+ display: flex;
+ flex-direction: column;
}
.setting-row {
display: flex;
- gap: 24px;
align-items: flex-start;
+ justify-content: space-between;
+ padding: 16px 0;
+ border-bottom: 1px solid var(--td-component-stroke);
+
+ &:last-child {
+ border-bottom: none;
+ }
}
.setting-info {
- flex: 0 0 220px;
-}
+ flex: 0 0 40%;
+ max-width: 40%;
+ padding-right: 24px;
-.setting-info label {
- font-weight: 500;
- display: block;
- margin-bottom: 4px;
-}
+ label {
+ font-size: 15px;
+ font-weight: 500;
+ color: var(--td-text-color-primary);
+ display: block;
+ margin-bottom: 4px;
+ }
-.setting-info .desc {
- font-size: 12px;
- color: var(--td-text-color-secondary, #4e5969);
- margin: 0;
+ .desc {
+ font-size: 13px;
+ color: var(--td-text-color-secondary);
+ margin: 0;
+ line-height: 1.5;
+ }
}
.setting-control {
- flex: 1;
+ flex: 0 0 55%;
+ max-width: 55%;
display: flex;
flex-direction: column;
+ align-items: flex-start;
+ gap: 6px;
+}
+
+.select-option {
+ display: inline-flex;
+ align-items: center;
gap: 8px;
}
.option-hint {
font-size: 12px;
- color: var(--td-text-color-secondary, #4e5969);
+ color: var(--td-text-color-placeholder);
margin: 0;
-}
+ line-height: 1.4;
-.change-warning {
- color: var(--td-error-color, #d54941);
+ &.change-warning {
+ color: var(--td-warning-color);
+ }
}
.go-settings {
- font-size: 12px;
+ font-size: 13px;
color: var(--td-brand-color, #0052d9);
+ margin-top: 8px;
text-decoration: none;
-}
-
-.go-settings:hover {
- text-decoration: underline;
-}
-.select-option {
- display: flex;
- align-items: center;
- gap: 8px;
-}
-
-.loading-inline {
- display: flex;
- align-items: center;
- gap: 8px;
- font-size: 13px;
- color: var(--td-text-color-secondary, #4e5969);
+ &:hover {
+ text-decoration: underline;
+ }
}
</style>