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: "分组方式",
@@ -72,6 +72,25 @@ func (r *sessionRepository) GetByID(ctx context.Context, tenantID uint64, id str
return &session, nil
}
// GetIMPlatform returns the IM platform bound to a session, or "" when none.
// It intentionally ignores soft-deleted mappings' visibility rules used by
// QueryPaged: any mapping (active or cleared) marks the session as IM-origin.
func (r *sessionRepository) GetIMPlatform(
ctx context.Context, tenantID uint64, sessionID string,
) (string, error) {
var platform string
err := r.db.WithContext(ctx).
Table("im_channel_sessions AS ics").
Joins("JOIN sessions AS s ON s.id = ics.session_id").
Where("ics.session_id = ? AND s.tenant_id = ?", sessionID, tenantID).
Limit(1).
Pluck("ics.platform", &platform).Error
if err != nil {
return "", err
}
return platform, nil
}
// GetByTenantID retrieves all sessions for a tenant
func (r *sessionRepository) GetByTenantID(ctx context.Context, tenantID uint64, userID string) ([]*types.Session, error) {
var sessions []*types.Session
@@ -169,6 +188,12 @@ func (r *sessionRepository) QueryPaged(
switch lower {
case "":
return db
case types.SessionSourceAPI:
// Tenant-wide view of API-key sessions. Their owner id is
// "api_tenant_key:<tenantID>:<keyID>", so a prefix match selects
// every key's sessions. The service layer already enforced Admin+
// and cleared the per-user scope for this source.
return db.Where("s.user_id LIKE ?", types.SessionOwnerAPITenantKeyPrefix+"%")
case "web":
// User web chats only — exclude embed-widget sessions (same IM-null row).
return db.Where(
@@ -245,3 +245,49 @@ func TestSessionRepositoryQueryPagedSplitsWebAndEmbedSessions(t *testing.T) {
require.NoError(t, err)
require.Equal(t, []string{embed.ID}, listItemIDsForTest(embedItems))
}
func TestSessionRepositoryGetIMPlatform(t *testing.T) {
repo, db := newSessionRepositoryForTest(t)
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
ctx := context.Background()
imSession := createSessionForTest(t, db, 1, "alice")
require.NoError(t, db.Create(&testIMChannelSession{
ID: "ics-1", SessionID: imSession.ID, Platform: "feishu",
}).Error)
webSession := createSessionForTest(t, db, 1, "alice")
platform, err := repo.GetIMPlatform(ctx, 1, imSession.ID)
require.NoError(t, err)
require.Equal(t, "feishu", platform)
platform, err = repo.GetIMPlatform(ctx, 1, webSession.ID)
require.NoError(t, err)
require.Equal(t, "", platform)
// Cross-tenant lookup must not leak the mapping.
platform, err = repo.GetIMPlatform(ctx, 2, imSession.ID)
require.NoError(t, err)
require.Equal(t, "", platform)
}
func TestSessionRepositoryQueryPagedAPISourceReturnsAllTenantAPIKeySessions(t *testing.T) {
repo, db := newSessionRepositoryForTest(t)
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
ctx := context.Background()
// Two different API keys plus a web user and a cross-tenant API session.
key1 := createSessionForTest(t, db, 1, types.SessionOwnerAPITenantKeyPrefix+"1:10")
key2 := createSessionForTest(t, db, 1, types.SessionOwnerAPITenantKeyPrefix+"1:20")
_ = createSessionForTest(t, db, 1, "alice")
_ = createSessionForTest(t, db, 2, types.SessionOwnerAPITenantKeyPrefix+"2:30")
// The admin view clears UserID, so every API-key session in the tenant is
// returned regardless of which key created it.
items, total, err := repo.QueryPaged(ctx, &types.SessionListQuery{
TenantID: 1, UserID: "", Source: types.SessionSourceAPI, Page: 1, PageSize: 50,
})
require.NoError(t, err)
require.EqualValues(t, 2, total)
require.ElementsMatch(t, []string{key1.ID, key2.ID}, listItemIDsForTest(items))
}
+4 -4
View File
@@ -108,7 +108,7 @@ func (s *messageService) GetMessage(ctx context.Context, sessionID string, messa
tenantID := types.MustTenantIDFromContext(ctx)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
@@ -137,7 +137,7 @@ func (s *messageService) GetMessagesBySession(ctx context.Context,
tenantID := types.MustTenantIDFromContext(ctx)
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
@@ -171,7 +171,7 @@ func (s *messageService) GetRecentMessagesBySession(ctx context.Context,
return nil, errors.New("workspace ID not found in context")
}
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
@@ -204,7 +204,7 @@ func (s *messageService) GetMessagesBySessionBeforeTime(ctx context.Context,
return nil, errors.New("workspace ID not found in context")
}
logger.Infof(ctx, "Checking if session exists, tenant ID: %d", tenantID)
_, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), sessionID)
_, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, sessionUserIDForLookup(ctx), sessionID)
if err != nil {
logger.Errorf(ctx, "Failed to get session: %v", err)
return nil, err
+46 -2
View File
@@ -22,6 +22,31 @@ func sessionUserIDFromContext(ctx context.Context) string {
return types.SessionOwnerIDFromContext(ctx)
}
// loadSessionForRead loads a session honoring the caller's per-user scope, with
// an Admin+ fallback that additionally permits reading tenant API-key sessions
// (owner id "api_tenant_key:<tenantID>:<keyID>"). This lets a tenant
// Owner/admin open sessions created via API keys — which are otherwise isolated
// per key — from the Web console, without exposing other users' personal
// sessions. Write paths keep the strict scope and must not use this helper.
func loadSessionForRead(
ctx context.Context,
repo interfaces.SessionRepository,
tenantID uint64,
ownerID, sessionID string,
) (*types.Session, error) {
session, err := repo.Get(ctx, tenantID, ownerID, sessionID)
if err == nil || !stderrors.Is(err, apperrors.ErrSessionNotFound) {
return session, err
}
if types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
if s, e := repo.GetByID(ctx, tenantID, sessionID); e == nil &&
strings.HasPrefix(s.UserID, types.SessionOwnerAPITenantKeyPrefix) {
return s, nil
}
}
return nil, err
}
// generateEventID generates a unique event ID with type suffix for better traceability
func generateEventID(suffix string) string {
return fmt.Sprintf("%s-%s", uuid.New().String()[:8], suffix)
@@ -120,7 +145,7 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
logger.Infof(ctx, "Retrieving session, ID: %s, tenant ID: %d", id, tenantID)
// Get session from repository
session, err := s.sessionRepo.Get(ctx, tenantID, userID, id)
session, err := loadSessionForRead(ctx, s.sessionRepo, tenantID, userID, id)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"session_id": id,
@@ -129,6 +154,14 @@ func (s *sessionService) GetSession(ctx context.Context, id string) (*types.Sess
return nil, err
}
// Best-effort IM origin so the Web console can classify the session's
// folder on read; a lookup failure must not fail the detail request.
if platform, pErr := s.sessionRepo.GetIMPlatform(ctx, tenantID, session.ID); pErr == nil {
session.IMPlatform = platform
} else {
logger.Warnf(ctx, "Failed to resolve IM platform for session %s: %v", session.ID, pErr)
}
logger.Infof(ctx, "Session retrieved successfully, ID: %s, tenant ID: %d", session.ID, session.TenantID)
return session, nil
}
@@ -211,7 +244,18 @@ func (s *sessionService) ListSessions(
query = &types.SessionListQuery{}
}
query.TenantID = types.MustTenantIDFromContext(ctx)
if uid := types.SessionOwnerIDFromContext(ctx); uid != "" {
// The "api" source is a tenant-wide admin view over API-key sessions, which
// are otherwise isolated per key. Gate it behind Admin+ and drop the
// per-user owner scope so the caller sees every key's sessions; everyone
// else stays scoped to their own principal.
if strings.EqualFold(strings.TrimSpace(query.Source), types.SessionSourceAPI) {
if !types.TenantRoleFromContext(ctx).HasPermission(types.TenantRoleAdmin) {
return nil, apperrors.NewForbiddenError(
"listing API-key sessions requires tenant admin or owner role",
)
}
query.UserID = ""
} else if uid := types.SessionOwnerIDFromContext(ctx); uid != "" {
query.UserID = uid
}
@@ -140,3 +140,76 @@ func TestGetSessionIsScopedToAPIExternalUser(t *testing.T) {
require.NoError(t, err)
require.Equal(t, tenantSession.ID, got.ID)
}
func TestGetSessionAllowsAdminToOpenAPIKeySessions(t *testing.T) {
svc, db := newTestSessionService(t)
apiSession := &types.Session{
TenantID: 1,
UserID: types.SessionOwnerAPITenantKeyPrefix + "1:10",
Title: "api key session",
}
require.NoError(t, db.Create(apiSession).Error)
otherUserSession := &types.Session{
TenantID: 1,
UserID: "bob",
Title: "bob private session",
}
require.NoError(t, db.Create(otherUserSession).Error)
// A non-admin web user cannot open the API-key session.
viewerCtx := testSessionScopeContext(1, "alice")
_, err := svc.GetSession(viewerCtx, apiSession.ID)
require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
// An admin can open the API-key session.
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
got, err := svc.GetSession(adminCtx, apiSession.ID)
require.NoError(t, err)
require.Equal(t, apiSession.ID, got.ID)
// The admin fallback is limited to API-key sessions; another user's
// personal session stays hidden.
_, err = svc.GetSession(adminCtx, otherUserSession.ID)
require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
}
func TestListSessionsAPISourceRequiresAdminAndReturnsAllKeys(t *testing.T) {
svc, db := newTestSessionService(t)
require.NoError(t, db.AutoMigrate(&testListSessionsIMChannelSession{}))
key1 := &types.Session{TenantID: 1, UserID: types.SessionOwnerAPITenantKeyPrefix + "1:10", Title: "key1"}
key2 := &types.Session{TenantID: 1, UserID: types.SessionOwnerAPITenantKeyPrefix + "1:20", Title: "key2"}
web := &types.Session{TenantID: 1, UserID: "alice", Title: "alice web"}
require.NoError(t, db.Create(key1).Error)
require.NoError(t, db.Create(key2).Error)
require.NoError(t, db.Create(web).Error)
// A non-admin (viewer) web user is rejected.
viewerCtx := testSessionScopeContext(1, "alice")
_, err := svc.ListSessions(viewerCtx, &types.SessionListQuery{Source: types.SessionSourceAPI})
require.Error(t, err)
var appErr *apperrors.AppError
require.ErrorAs(t, err, &appErr)
require.Equal(t, apperrors.ErrForbidden, appErr.Code)
// An admin sees every API-key session in the tenant, not just their own.
adminCtx := context.WithValue(testSessionScopeContext(1, "alice"), types.TenantRoleContextKey, types.TenantRoleAdmin)
result, err := svc.ListSessions(adminCtx, &types.SessionListQuery{Source: types.SessionSourceAPI})
require.NoError(t, err)
require.EqualValues(t, 2, result.Total)
}
// testListSessionsIMChannelSession lets QueryPaged's LEFT JOIN resolve against a
// real table in the in-memory SQLite database.
type testListSessionsIMChannelSession struct {
ID uint64 `gorm:"primaryKey;autoIncrement"`
SessionID string `gorm:"column:session_id"`
Platform string `gorm:"column:platform"`
ChatID string `gorm:"column:chat_id"`
ThreadID string `gorm:"column:thread_id"`
UserID string `gorm:"column:user_id"`
AgentID string `gorm:"column:agent_id"`
IMChannelID string `gorm:"column:im_channel_id"`
}
func (testListSessionsIMChannelSession) TableName() string { return "im_channel_sessions" }
+1 -1
View File
@@ -201,7 +201,7 @@ func (h *Handler) GetSession(c *gin.Context) {
// @Param page query int false "页码"
// @Param page_size query int false "每页数量"
// @Param keyword query string false "标题模糊搜索"
// @Param source query string false "来源过滤:web / feishu / wechat / slack / ..."
// @Param source query string false "来源过滤:web / embed / api(API Key 会话,需 Admin+)/ feishu / wechat / slack / ..."
// @Param agent_id query string false "按 Agent 过滤(仅对 IM 会话生效)"
// @Success 200 {object} map[string]interface{} "会话列表"
// @Failure 400 {object} errors.AppError "请求参数错误"
+4
View File
@@ -68,6 +68,10 @@ type SessionRepository interface {
// GetByID loads a session by tenant and id without user scoping. Callers
// must enforce access (e.g. embed channel + session signature).
GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error)
// GetIMPlatform returns the IM platform bound to a session via
// im_channel_sessions, or "" when the session has no IM mapping. Used to
// classify a session's origin folder on read without a full list query.
GetIMPlatform(ctx context.Context, tenantID uint64, sessionID string) (string, error)
// GetByTenantID gets all sessions visible to the tenant/user scope.
GetByTenantID(ctx context.Context, tenantID uint64, userID string) ([]*types.Session, error)
// GetPagedByTenantID gets paged sessions visible to the tenant/user scope.
+6 -1
View File
@@ -20,6 +20,11 @@ const (
// across chat sessions within the same channel.
const EmbedVisitorHeader = "X-Embed-Visitor"
// SessionOwnerAPITenantKeyPrefix prefixes sessions.user_id for rows created by a
// tenant API key. The full owner id is "api_tenant_key:<tenantID>:<keyID>", so a
// LIKE '<prefix>%' selects every API-key session in the tenant.
const SessionOwnerAPITenantKeyPrefix = "api_tenant_key:"
// Principal represents the terminal caller for per-subject isolation features.
// It is intentionally separate from UserID: many principals, such as IM users
// or embed visitors, are not WeKnora accounts and must not imply RBAC rights.
@@ -164,7 +169,7 @@ func SessionOwnerIDFromContext(ctx context.Context) string {
case PrincipalAPITenant:
if scope, ok := TenantAPIKeyScopeFromContext(ctx); ok && scope.KeyID > 0 {
if tenantID, ok := TenantIDFromContext(ctx); ok && tenantID > 0 {
return fmt.Sprintf("api_tenant_key:%d:%d", tenantID, scope.KeyID)
return fmt.Sprintf("%s%d:%d", SessionOwnerAPITenantKeyPrefix, tenantID, scope.KeyID)
}
}
}
+14 -1
View File
@@ -118,6 +118,12 @@ type Session struct {
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
// IMPlatform is the originating IM platform (e.g. "feishu", "wecom") when
// this session is bound to an IM channel. It is not stored on the sessions
// table (it lives in im_channel_sessions) and is populated on read so the
// Web console can classify a session's origin folder without a list query.
IMPlatform string `json:"im_platform,omitempty" gorm:"-"`
// Association relationship, not stored in the database
Messages []Message `json:"-" gorm:"foreignKey:SessionID"`
}
@@ -127,11 +133,18 @@ func (s *Session) BeforeCreate(tx *gorm.DB) (err error) {
return nil
}
// SessionSourceAPI is the source filter that lists every session created via a
// tenant API key across the whole tenant. It is an admin-only view: the service
// layer requires Admin+ and drops the per-user owner scope so a tenant
// Owner/admin can observe API-key traffic that is otherwise isolated per key.
const SessionSourceAPI = "api"
// SessionListQuery bundles the parameters for listing sessions.
// UserID empty means "tenant-wide" (used by API-key callers / legacy rows).
// Keyword matches title ILIKE '%keyword%'.
// Source values: "web" (user chats, no IM/embed), "embed" / "embed:{channelID}",
// or an IM platform name (e.g. "feishu", "wechat").
// "api" (all API-key sessions, Admin+ only), or an IM platform name
// (e.g. "feishu", "wechat").
// AgentID currently only filters sessions that have an IM channel mapping.
type SessionListQuery struct {
TenantID uint64