feat(session): add admin API session bucket and stabilize sidebar filter

Let tenant admins list and open API-key sessions from the Web console while
keeping per-key isolation for everyone else. Pin the session source filter so
it no longer jumps when switching buckets, and resolve session origin on read
so deep links stay in sync with the active folder after refresh.
This commit is contained in:
wizardchen
2026-07-20 18:23:35 +08:00
committed by lyingbug
parent eab91d2f7f
commit 76a4ffe525
18 changed files with 317 additions and 65 deletions
@@ -6,9 +6,9 @@
<button ref="triggerRef" type="button" class="session-source-filter__trigger" :aria-expanded="open"
aria-haspopup="listbox" @click.stop="toggleOpen">
<span class="session-source-filter__leading">
<img v-if="!inline && currentOption?.logo" :src="currentOption.logo" :alt="currentOption.label"
<img v-if="currentOption?.logo" :src="currentOption.logo" :alt="currentOption.label"
class="session-source-filter__logo" />
<t-icon v-else-if="!inline" :name="iconFor(currentOption)" class="session-source-filter__icon" size="14px" />
<t-icon v-else :name="iconFor(currentOption)" class="session-source-filter__icon" size="14px" />
<span class="session-source-filter__label" :title="currentOption?.label">{{ currentOption?.label }}</span>
</span>
<t-icon v-if="inline" name="chevron-down" class="session-source-filter__chevron"
@@ -75,6 +75,7 @@ const currentOption = computed(() =>
const iconFor = (item: SourceItem | undefined): string => {
if (!item) return 'chat'
if (item.value === DEFAULT_SESSION_BUCKET_KEY) return 'chat'
if (item.value === 'api') return 'server'
if (item.value.startsWith('embed:')) return 'code'
return 'link'
}
@@ -153,7 +154,7 @@ onBeforeUnmount(() => {
max-width: 100%;
.session-source-filter__leading {
gap: 0;
gap: 4px;
flex: 0 1 auto;
}
}
+51 -50
View File
@@ -101,9 +101,12 @@
</div>
<!-- 历史会话:按来源筛选后统一按日期分组展示 -->
<div class="submenu" v-if="!uiStore.sidebarCollapsed"
:class="{ 'submenu--scope-fallback': showSessionScopeFallback }">
<div v-if="showSessionScopeFallback" class="session-list-scope-fallback">
<div class="submenu" v-if="!uiStore.sidebarCollapsed">
<!-- Stable, always-mounted source filter: reserving its row here
(instead of embedding it in the first date group, which
appears/disappears while a bucket loads) prevents the
top-right control from jumping when switching session type. -->
<div v-if="showSessionSourceFilter && !batchMode" class="session-list-scope-header">
<SessionSourceFilter inline :emphasized="sessionScopeFilterPinned" :sources="sessionSourceOptions"
:current="activeSessionBucketKey" @select="switchSessionBucket" />
</div>
@@ -130,15 +133,11 @@
<div class="submenu_empty">{{ t('menu.noSessions') }}</div>
</template>
<template v-else>
<template v-for="(group, groupIndex) in filteredGroupedSessions" :key="group.key">
<div v-if="group.label" class="timeline_header session-list-row session-list-row--flat"
:class="{ 'timeline_header--with-scope': groupIndex === 0 && showSessionSourceFilter && !batchMode }">
<template v-for="group in filteredGroupedSessions" :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>
<SessionSourceFilter v-if="groupIndex === 0 && showSessionSourceFilter && !batchMode"
inline :emphasized="sessionScopeFilterPinned" :sources="sessionSourceOptions"
:current="activeSessionBucketKey" @select="switchSessionBucket" />
</div>
<div v-for="subitem in group.items" :key="subitem.id"
class="submenu_item_p session-chat-row" :class="{
@@ -202,7 +201,7 @@
import { storeToRefs } from 'pinia';
import { onMounted, onUnmounted, watch, computed, ref, h, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getSessionsList, batchDelSessions, deleteAllSessions } from "@/api/chat/index";
import { getSessionsList, batchDelSessions, deleteAllSessions, getSession } from "@/api/chat/index";
import { useChatResourcesStore } from '@/stores/chatResources';
import { listAllIMChannels } from '@/api/agent/index';
import SessionSidebarRow from './SessionSidebarRow.vue';
@@ -480,15 +479,6 @@ const filteredGroupedSessions = computed(() => {
);
});
const showSessionScopeFallback = computed(() => {
if (!showSessionSourceFilter.value || batchMode.value) return false;
if (sessionListBooting.value && !hasAnySession.value) return true;
const bucket = activeBucket.value;
if (bucket?.loading && !bucket.loaded && filteredGroupedSessions.value.length === 0) return true;
if (bucket?.loaded && filteredGroupedSessions.value.length === 0) return true;
return false;
});
const refreshSessionListScrollability = async () => {
await nextTick();
const container = scrollContainer.value;
@@ -702,6 +692,7 @@ const mapSessionRow = (item: any) => ({
pinned_at: item.pinned_at || null,
im_platform: item.im_platform || '',
description: item.description || '',
user_id: item.user_id || '',
});
const syncMenuStoreFromBuckets = () => {
@@ -722,6 +713,7 @@ const menuChildToSessionRow = (item: Record<string, unknown>): SessionForGroupin
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 : '',
user_id: typeof item.user_id === 'string' ? item.user_id : '',
};
};
@@ -754,7 +746,9 @@ const rebuildBucketDefinitions = () => buildBucketDefinitions(
web: t('menu.myChats'),
imPlatform: (platform) => t(`agentEditor.im.${platform}`),
embedChannel: (name) => name,
api: t('menu.apiChats'),
},
{ includeApiBucket: authStore.hasRole('admin') },
);
/** 首屏轻量探测各渠道是否有会话(page_size=1 只取 total),避免展示空文件夹 */
@@ -837,6 +831,27 @@ const syncActiveBucketFromChat = async (sessionId: string | undefined) => {
bucketKey = originGroupKey(resolveSessionOrigin(menuChildToSessionRow(fromStore)));
}
}
// On a hard refresh only the web bucket is loaded, so a session opened from
// any other folder (IM, embed, or the admin-only API folder) isn't in any
// bucket or the menu store. Fetch its detail and classify its origin folder
// so the sidebar stays in sync with the chat pane instead of snapping back
// to "my chats". Only switch when that folder is actually present.
if (!bucketKey) {
try {
const res: any = await getSession(sessionId);
const candidate = originGroupKey(resolveSessionOrigin({
id: sessionId,
im_platform: res?.data?.im_platform || '',
description: res?.data?.description || '',
user_id: res?.data?.user_id || '',
}));
if (sessionBuckets.value[candidate]) {
bucketKey = candidate;
}
} catch {
// Fall through: leave the default bucket active on lookup failure.
}
}
if (!bucketKey || bucketKey === activeSessionBucketKey.value) return;
activeSessionBucketKey.value = bucketKey;
@@ -1460,6 +1475,7 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
}
.submenu {
position: relative;
font-family: var(--app-font-family);
font-size: 14px;
font-style: normal;
@@ -1550,48 +1566,33 @@ const onDragHandleMouseDown = (e: MouseEvent) => {
white-space: nowrap;
}
.timeline_header--with-scope {
justify-content: space-between;
gap: 10px;
:deep(.session-source-filter--inline) {
flex: 0 1 auto;
min-width: 0;
max-width: 52%;
opacity: 0;
transition: opacity 0.15s ease;
}
&:hover :deep(.session-source-filter--inline),
&:focus-within :deep(.session-source-filter--inline),
:deep(.session-source-filter--inline.session-source-filter--emphasized) {
opacity: 1;
}
}
.submenu--scope-fallback {
position: relative;
padding-top: 18px;
}
.session-list-scope-fallback {
// Stable filter control: always mounted and absolutely pinned to the list's
// top-right so it visually sits on the first row (e.g. beside "近30天") and
// never jumps when switching session type reloads a bucket. It overlays the
// empty right side of the first header row, so it needs no reserved height.
.session-list-scope-header {
position: absolute;
top: 1px;
top: 4px;
right: 10px;
z-index: 1;
z-index: 2;
display: flex;
justify-content: flex-end;
max-width: calc(100% - var(--sidebar-inset-x) - 10px);
:deep(.session-source-filter--inline) {
flex: 0 1 auto;
min-width: 0;
max-width: 100%;
opacity: 0;
transition: opacity 0.15s ease;
}
}
&:hover :deep(.session-source-filter--inline),
:deep(.session-source-filter--inline.session-source-filter--emphasized) {
opacity: 1;
}
.submenu:hover .session-list-scope-header :deep(.session-source-filter--inline),
.session-list-scope-header:hover :deep(.session-source-filter--inline),
.session-list-scope-header:focus-within :deep(.session-source-filter--inline),
.session-list-scope-header :deep(.session-source-filter--inline.session-source-filter--emphasized) {
opacity: 1;
}
.submenu_item_p {
@@ -13,6 +13,7 @@ import {
const sourceLabels = {
web: 'Web',
api: 'API',
embedFallback: 'Embed',
embedChannel: (id: string) => `Embed ${id}`,
imPlatform: (p: string) => `IM ${p}`,
@@ -31,6 +32,10 @@ test('resolveSessionOrigin distinguishes web, IM, and embed sessions', () => {
}),
{ kind: 'embed', channelId: 'ch-1' },
)
assert.deepEqual(
resolveSessionOrigin({ id: '4', user_id: 'api_tenant_key:1:10' }),
{ kind: 'api' },
)
})
test('configuredPlatforms returns distinct platform keys in first-seen order', () => {
@@ -8,6 +8,9 @@ export const DEFAULT_SESSION_GROUP_MODE: SessionGroupMode = 'none'
/** Mirrors backend types.EmbedSessionMarkerPrefix */
export const EMBED_SESSION_MARKER_PREFIX = 'embed_channel:'
/** Mirrors backend types.SessionOwnerAPITenantKeyPrefix (sessions.user_id owner). */
export const API_SESSION_OWNER_PREFIX = 'api_tenant_key:'
export interface SessionForGrouping {
id: string
title?: string
@@ -16,6 +19,7 @@ export interface SessionForGrouping {
updated_at?: string
im_platform?: string
description?: string
user_id?: string
originalIndex?: number
}
@@ -29,6 +33,7 @@ export type SessionOrigin =
| { kind: 'web' }
| { kind: 'im'; platform: string }
| { kind: 'embed'; channelId: string }
| { kind: 'api' }
export interface GroupModeOption {
value: SessionGroupMode
@@ -37,6 +42,7 @@ export interface GroupModeOption {
export interface SourceGroupLabels {
web: string
api: string
embedFallback: string
embedChannel: (channelId: string) => string
imPlatform: (platform: string) => string
@@ -86,6 +92,9 @@ export function resolveSessionOrigin(session: SessionForGrouping): SessionOrigin
const channelId = desc.slice(EMBED_SESSION_MARKER_PREFIX.length).trim()
if (channelId) return { kind: 'embed', channelId }
}
if ((session.user_id || '').startsWith(API_SESSION_OWNER_PREFIX)) {
return { kind: 'api' }
}
return { kind: 'web' }
}
@@ -97,6 +106,8 @@ export function originGroupKey(origin: SessionOrigin): string {
return `im:${origin.platform}`
case 'embed':
return `embed:${origin.channelId}`
case 'api':
return 'api'
}
}
@@ -108,6 +119,8 @@ function labelForOrigin(
switch (origin.kind) {
case 'web':
return labels.web
case 'api':
return labels.api
case 'im':
return labels.imPlatform(origin.platform)
case 'embed': {
@@ -5,7 +5,7 @@ import type { SessionForGrouping } from './sessionGrouping'
export const SIDEBAR_BUCKET_PAGE_SIZE = 30
export type SidebarBucketKind = 'web' | 'im' | 'embed'
export type SidebarBucketKind = 'web' | 'im' | 'embed' | 'api'
export interface SidebarSessionBucket {
key: string
@@ -60,13 +60,18 @@ export function applyBucketCountProbe(
}
export function isChannelBucket(bucket: SidebarSessionBucket): boolean {
return bucket.kind === 'im' || bucket.kind === 'embed'
return bucket.kind === 'im' || bucket.kind === 'embed' || bucket.kind === 'api'
}
export function isChannelBucketKey(key: string): boolean {
return key.startsWith('im:') || key.startsWith('embed:')
return key.startsWith('im:') || key.startsWith('embed:') || key === API_SESSION_BUCKET_KEY
}
// API_SESSION_BUCKET_KEY is the admin-only bucket that lists every API-key
// session in the tenant. It is treated like a channel folder: probed for a
// count first and only surfaced in the source filter when it has sessions.
export const API_SESSION_BUCKET_KEY = 'api'
export function buildBucketDefinitions(
imPlatforms: string[],
embedChannels: Record<string, string>,
@@ -74,7 +79,9 @@ export function buildBucketDefinitions(
web: string
imPlatform: (platform: string) => string
embedChannel: (name: string) => string
api: string
},
options: { includeApiBucket?: boolean } = {},
): BucketDefinition[] {
const imDefs = imPlatforms.map((platform) => ({
key: `im:${platform}`,
@@ -89,9 +96,20 @@ export function buildBucketDefinitions(
label: labels.embedChannel(name || id.slice(0, 8)),
kind: 'embed' as const,
}))
const apiDefs: BucketDefinition[] = options.includeApiBucket
? [
{
key: API_SESSION_BUCKET_KEY,
apiSource: API_SESSION_BUCKET_KEY,
label: labels.api,
kind: 'api' as const,
},
]
: []
return [
...imDefs,
...embedDefs,
...apiDefs,
{
key: 'web',
apiSource: 'web',
+1
View File
@@ -32,6 +32,7 @@ export default {
expandSidebar: 'Expand Sidebar',
logoutSuccess: 'Logged out successfully',
myChats: 'My chats',
apiChats: 'API sessions',
embedChats: 'Web embed',
embedChannelNamed: 'Web embed · {name}',
groupBy: 'Group by',
+1
View File
@@ -32,6 +32,7 @@ export default {
expandSidebar: "사이드바 펼치기",
logoutSuccess: "로그아웃되었습니다",
myChats: "내 대화",
apiChats: "API 세션",
embedChats: "웹 임베드",
embedChannelNamed: "웹 임베드 · {name}",
groupBy: "그룹화",
+1
View File
@@ -29,6 +29,7 @@ export default {
expandSidebar: 'Развернуть боковую панель',
logoutSuccess: 'Вы вышли из системы',
myChats: 'Мои чаты',
apiChats: 'Сессии API',
embedChats: 'Веб-встраивание',
embedChannelNamed: 'Веб-встраивание · {name}',
groupBy: 'Группировать',
+1
View File
@@ -32,6 +32,7 @@ export default {
expandSidebar: "展开侧边栏",
logoutSuccess: "已退出登录",
myChats: "我的对话",
apiChats: "API 会话",
embedChats: "网页嵌入",
embedChannelNamed: "网页嵌入 · {name}",
groupBy: "分组方式",