feat: classify externally managed sessions by source

This commit is contained in:
姚章浩
2026-08-03 15:05:12 +08:00
parent 7ccf3365f0
commit 027965da0a
10 changed files with 110 additions and 10 deletions
+3 -2
View File
@@ -225,6 +225,7 @@ import {
flattenBucketItems, flattenBucketItems,
isChannelBucket, isChannelBucket,
isChannelBucketKey, isChannelBucketKey,
mergeConfiguredAndExternalSessionPlatforms,
mergeBucketPage, mergeBucketPage,
prependSessionToWebBucket, prependSessionToWebBucket,
removeSessionFromBuckets, removeSessionFromBuckets,
@@ -936,9 +937,9 @@ async function loadCurrentKbInfo(kbId: string) {
const loadSessionOriginMeta = async () => { const loadSessionOriginMeta = async () => {
try { try {
const res: any = await listAllIMChannels(); const res: any = await listAllIMChannels();
imPlatforms.value = configuredPlatforms(res?.data || []); imPlatforms.value = mergeConfiguredAndExternalSessionPlatforms(configuredPlatforms(res?.data || []));
} catch { } catch {
imPlatforms.value = []; imPlatforms.value = mergeConfiguredAndExternalSessionPlatforms([]);
} }
try { try {
const res: any = await listAllEmbedChannels(); const res: any = await listAllEmbedChannels();
@@ -5,6 +5,7 @@ import {
applyBucketCountProbe, applyBucketCountProbe,
bucketVisible, bucketVisible,
createEmptyBucket, createEmptyBucket,
mergeConfiguredAndExternalSessionPlatforms,
prependSessionToWebBucket, prependSessionToWebBucket,
type BucketDefinition, type BucketDefinition,
} from './sessionSidebarBuckets.ts' } from './sessionSidebarBuckets.ts'
@@ -56,3 +57,8 @@ test('prependSessionToWebBucket is idempotent for existing session', () => {
const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' }) const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' })
assert.equal(next, bucket) assert.equal(next, bucket)
}) })
test('mergeConfiguredAndExternalSessionPlatforms always probes dingtalk once', () => {
assert.deepEqual(mergeConfiguredAndExternalSessionPlatforms(['feishu']), ['feishu', 'dingtalk'])
assert.deepEqual(mergeConfiguredAndExternalSessionPlatforms(['dingtalk', 'feishu']), ['dingtalk', 'feishu'])
})
@@ -4,6 +4,7 @@
import type { SessionForGrouping } from './sessionGrouping' import type { SessionForGrouping } from './sessionGrouping'
export const SIDEBAR_BUCKET_PAGE_SIZE = 30 export const SIDEBAR_BUCKET_PAGE_SIZE = 30
const EXTERNAL_SESSION_PLATFORMS = ['dingtalk']
export type SidebarBucketKind = 'web' | 'im' | 'embed' export type SidebarBucketKind = 'web' | 'im' | 'embed'
@@ -30,6 +31,14 @@ export interface BucketDefinition {
platform?: string platform?: string
} }
export function mergeConfiguredAndExternalSessionPlatforms(configured: string[]): string[] {
const merged = [...configured]
for (const platform of EXTERNAL_SESSION_PLATFORMS) {
if (!merged.includes(platform)) merged.push(platform)
}
return merged
}
export function createEmptyBucket(def: BucketDefinition): SidebarSessionBucket { export function createEmptyBucket(def: BucketDefinition): SidebarSessionBucket {
return { return {
...def, ...def,
+9 -5
View File
@@ -155,13 +155,13 @@ func (r *sessionRepository) QueryPaged(
case "": case "":
return db return db
case "web": case "web":
// User web chats only — exclude embed-widget sessions (same IM-null row). // User web chats only — exclude embed widgets and externally managed sessions.
return db.Where( return db.Where(
"ics.id IS NULL AND (s.description = '' OR s.description NOT LIKE ?)", "ics.id IS NULL AND LOWER(COALESCE(s.source, '')) IN ('', 'web') AND (s.description = '' OR s.description NOT LIKE ?)",
embedPrefix+"%", embedPrefix+"%",
) )
case "embed": case "embed":
return db.Where("ics.id IS NULL AND s.description LIKE ?", embedPrefix+"%") return db.Where("ics.id IS NULL AND LOWER(COALESCE(s.source, '')) IN ('', 'web') AND s.description LIKE ?", embedPrefix+"%")
default: default:
if strings.HasPrefix(lower, "embed:") { if strings.HasPrefix(lower, "embed:") {
channelID := strings.TrimSpace(src[len("embed:"):]) channelID := strings.TrimSpace(src[len("embed:"):])
@@ -169,7 +169,7 @@ func (r *sessionRepository) QueryPaged(
return db.Where("ics.id IS NULL AND s.description = ?", embedPrefix+channelID) return db.Where("ics.id IS NULL AND s.description = ?", embedPrefix+channelID)
} }
} }
return db.Where("ics.platform = ?", lower) return db.Where("ics.platform = ? OR (ics.id IS NULL AND LOWER(COALESCE(s.source, '')) = ?)", lower, lower)
} }
} }
applyAgent := func(db *gorm.DB) *gorm.DB { applyAgent := func(db *gorm.DB) *gorm.DB {
@@ -202,7 +202,11 @@ func (r *sessionRepository) QueryPaged(
r.db.WithContext(ctx).Table("sessions AS s").Joins(joinClause), r.db.WithContext(ctx).Table("sessions AS s").Joins(joinClause),
))). ))).
Select(`s.*, Select(`s.*,
ics.platform AS im_platform, CASE
WHEN ics.platform IS NOT NULL AND ics.platform != '' THEN ics.platform
WHEN s.external_managed THEN s.source
ELSE ''
END AS im_platform,
ics.chat_id AS im_chat_id, ics.chat_id AS im_chat_id,
ics.thread_id AS im_thread_id, ics.thread_id AS im_thread_id,
ics.user_id AS im_user_id, ics.user_id AS im_user_id,
@@ -245,3 +245,32 @@ func TestSessionRepositoryQueryPagedSplitsWebAndEmbedSessions(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, []string{embed.ID}, listItemIDsForTest(embedItems)) require.Equal(t, []string{embed.ID}, listItemIDsForTest(embedItems))
} }
func TestSessionRepositoryQueryPagedClassifiesExternalDingTalkSessions(t *testing.T) {
repo, db := newSessionRepositoryForTest(t)
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
ctx := context.Background()
web := createSessionForTest(t, db, 1, "alice")
external := createSessionForTest(t, db, 1, "alice")
require.NoError(t, db.Model(&types.Session{}).Where("id = ?", external.ID).Updates(map[string]interface{}{
"source": "dingtalk",
"external_managed": true,
"external_system": "dobotai",
}).Error)
webItems, _, err := repo.QueryPaged(ctx, &types.SessionListQuery{
TenantID: 1, UserID: "alice", Source: "web", Page: 1, PageSize: 50,
})
require.NoError(t, err)
require.Equal(t, []string{web.ID}, listItemIDsForTest(webItems))
dingtalkItems, _, err := repo.QueryPaged(ctx, &types.SessionListQuery{
TenantID: 1, UserID: "alice", Source: "dingtalk", Page: 1, PageSize: 50,
})
require.NoError(t, err)
require.Equal(t, []string{external.ID}, listItemIDsForTest(dingtalkItems))
require.Equal(t, "dingtalk", dingtalkItems[0].Source)
require.True(t, dingtalkItems[0].ExternalManaged)
require.Equal(t, "dobotai", dingtalkItems[0].ExternalSystem)
}
+10 -3
View File
@@ -3,6 +3,7 @@ package session
import ( import (
stderrors "errors" stderrors "errors"
"net/http" "net/http"
"strings"
"github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/errors"
@@ -111,9 +112,15 @@ func (h *Handler) CreateSession(c *gin.Context) {
// Create session object with base properties // Create session object with base properties
createdSession := &types.Session{ createdSession := &types.Session{
TenantID: tenantID.(uint64), TenantID: tenantID.(uint64),
Title: request.Title, Title: request.Title,
Description: request.Description, Description: request.Description,
Source: strings.ToLower(strings.TrimSpace(request.Source)),
ExternalManaged: request.ExternalManaged,
ExternalSystem: strings.ToLower(strings.TrimSpace(request.ExternalSystem)),
}
if createdSession.Source == "" {
createdSession.Source = "web"
} }
// Attach the calling user as the session owner when available. // Attach the calling user as the session owner when available.
// API-key / legacy callers without a user id fall back to tenant-level visibility. // API-key / legacy callers without a user id fall back to tenant-level visibility.
+6
View File
@@ -12,6 +12,12 @@ type CreateSessionRequest struct {
Title string `json:"title"` Title string `json:"title"`
// Description for the session (optional) // Description for the session (optional)
Description string `json:"description"` Description string `json:"description"`
// Source identifies the originating channel (for example web or dingtalk).
Source string `json:"source"`
// ExternalManaged marks a session whose lifecycle is owned outside WeKnora.
ExternalManaged bool `json:"external_managed"`
// ExternalSystem identifies the external owner (for example dobotai).
ExternalSystem string `json:"external_system"`
} }
// GenerateTitleRequest defines the request structure for generating a session title // GenerateTitleRequest defines the request structure for generating a session title
+6
View File
@@ -79,6 +79,12 @@ type Session struct {
Title string `json:"title"` Title string `json:"title"`
// Description // Description
Description string `json:"description"` Description string `json:"description"`
// Source identifies where the session originated (for example web or dingtalk).
Source string `json:"source" gorm:"type:varchar(50);not null;default:'web';index"`
// ExternalManaged marks sessions whose lifecycle is owned by another system.
ExternalManaged bool `json:"external_managed" gorm:"not null;default:false"`
// ExternalSystem identifies the owning external system (for example dobotai).
ExternalSystem string `json:"external_system" gorm:"type:varchar(50);not null;default:''"`
// Tenant ID // Tenant ID
TenantID uint64 `json:"tenant_id" gorm:"index"` TenantID uint64 `json:"tenant_id" gorm:"index"`
// UserID is the owner of the session. Empty for legacy rows (visible at // UserID is the owner of the session. Empty for legacy rows (visible at
@@ -0,0 +1,12 @@
-- Migration: 000064_session_external_source (rollback)
-- Description: Remove structured source metadata from sessions.
DO $$ BEGIN RAISE NOTICE '[Migration 000064 rollback] Removing external session source metadata...'; END $$;
DROP INDEX IF EXISTS idx_sessions_source;
ALTER TABLE sessions
DROP COLUMN IF EXISTS external_system,
DROP COLUMN IF EXISTS external_managed,
DROP COLUMN IF EXISTS source;
DO $$ BEGIN RAISE NOTICE '[Migration 000064 rollback] External session source metadata removed'; END $$;
@@ -0,0 +1,20 @@
-- Migration: 000064_session_external_source
-- Description: Add structured source metadata for externally managed sessions.
DO $$ BEGIN RAISE NOTICE '[Migration 000064] Adding external session source metadata...'; END $$;
ALTER TABLE sessions
ADD COLUMN IF NOT EXISTS source VARCHAR(50) NOT NULL DEFAULT 'web',
ADD COLUMN IF NOT EXISTS external_managed BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS external_system VARCHAR(50) NOT NULL DEFAULT '';
CREATE INDEX IF NOT EXISTS idx_sessions_source
ON sessions(tenant_id, source, updated_at DESC);
-- Existing DobotAI sessions used this exact marker before structured fields existed.
UPDATE sessions
SET source = 'dingtalk',
external_managed = TRUE,
external_system = 'dobotai'
WHERE description = 'Managed by DobotAI; business state remains outside WeKnora';
DO $$ BEGIN RAISE NOTICE '[Migration 000064] External session source metadata ready'; END $$;