diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue index 1f35a33e..397725b3 100644 --- a/frontend/src/components/menu.vue +++ b/frontend/src/components/menu.vue @@ -225,6 +225,7 @@ import { flattenBucketItems, isChannelBucket, isChannelBucketKey, + mergeConfiguredAndExternalSessionPlatforms, mergeBucketPage, prependSessionToWebBucket, removeSessionFromBuckets, @@ -936,9 +937,9 @@ async function loadCurrentKbInfo(kbId: string) { const loadSessionOriginMeta = async () => { try { const res: any = await listAllIMChannels(); - imPlatforms.value = configuredPlatforms(res?.data || []); + imPlatforms.value = mergeConfiguredAndExternalSessionPlatforms(configuredPlatforms(res?.data || [])); } catch { - imPlatforms.value = []; + imPlatforms.value = mergeConfiguredAndExternalSessionPlatforms([]); } try { const res: any = await listAllEmbedChannels(); diff --git a/frontend/src/components/sessionSidebarBuckets.test.ts b/frontend/src/components/sessionSidebarBuckets.test.ts index e2d8fee4..4dd8fff6 100644 --- a/frontend/src/components/sessionSidebarBuckets.test.ts +++ b/frontend/src/components/sessionSidebarBuckets.test.ts @@ -5,6 +5,7 @@ import { applyBucketCountProbe, bucketVisible, createEmptyBucket, + mergeConfiguredAndExternalSessionPlatforms, prependSessionToWebBucket, type BucketDefinition, } from './sessionSidebarBuckets.ts' @@ -56,3 +57,8 @@ test('prependSessionToWebBucket is idempotent for existing session', () => { const next = prependSessionToWebBucket(bucket, { id: 'a', title: 'Same' }) assert.equal(next, bucket) }) + +test('mergeConfiguredAndExternalSessionPlatforms always probes dingtalk once', () => { + assert.deepEqual(mergeConfiguredAndExternalSessionPlatforms(['feishu']), ['feishu', 'dingtalk']) + assert.deepEqual(mergeConfiguredAndExternalSessionPlatforms(['dingtalk', 'feishu']), ['dingtalk', 'feishu']) +}) diff --git a/frontend/src/components/sessionSidebarBuckets.ts b/frontend/src/components/sessionSidebarBuckets.ts index 62da3faa..12b0028a 100644 --- a/frontend/src/components/sessionSidebarBuckets.ts +++ b/frontend/src/components/sessionSidebarBuckets.ts @@ -4,6 +4,7 @@ import type { SessionForGrouping } from './sessionGrouping' export const SIDEBAR_BUCKET_PAGE_SIZE = 30 +const EXTERNAL_SESSION_PLATFORMS = ['dingtalk'] export type SidebarBucketKind = 'web' | 'im' | 'embed' @@ -30,6 +31,14 @@ export interface BucketDefinition { 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 { return { ...def, diff --git a/internal/application/repository/session.go b/internal/application/repository/session.go index 250d13e8..3cad0ed6 100644 --- a/internal/application/repository/session.go +++ b/internal/application/repository/session.go @@ -155,13 +155,13 @@ func (r *sessionRepository) QueryPaged( case "": return db 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( - "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+"%", ) 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: if strings.HasPrefix(lower, "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.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 { @@ -202,7 +202,11 @@ func (r *sessionRepository) QueryPaged( r.db.WithContext(ctx).Table("sessions AS s").Joins(joinClause), ))). 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.thread_id AS im_thread_id, ics.user_id AS im_user_id, diff --git a/internal/application/repository/session_test.go b/internal/application/repository/session_test.go index 4c40e23b..0771cfae 100644 --- a/internal/application/repository/session_test.go +++ b/internal/application/repository/session_test.go @@ -245,3 +245,32 @@ func TestSessionRepositoryQueryPagedSplitsWebAndEmbedSessions(t *testing.T) { require.NoError(t, err) 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) +} diff --git a/internal/handler/session/handler.go b/internal/handler/session/handler.go index 3be73cc3..e06e3829 100644 --- a/internal/handler/session/handler.go +++ b/internal/handler/session/handler.go @@ -3,6 +3,7 @@ package session import ( stderrors "errors" "net/http" + "strings" "github.com/Tencent/WeKnora/internal/config" "github.com/Tencent/WeKnora/internal/errors" @@ -111,9 +112,15 @@ func (h *Handler) CreateSession(c *gin.Context) { // Create session object with base properties createdSession := &types.Session{ - TenantID: tenantID.(uint64), - Title: request.Title, - Description: request.Description, + TenantID: tenantID.(uint64), + Title: request.Title, + 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. // API-key / legacy callers without a user id fall back to tenant-level visibility. diff --git a/internal/handler/session/types.go b/internal/handler/session/types.go index 2bdc8137..e6fa1fe6 100644 --- a/internal/handler/session/types.go +++ b/internal/handler/session/types.go @@ -12,6 +12,12 @@ type CreateSessionRequest struct { Title string `json:"title"` // Description for the session (optional) 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 diff --git a/internal/types/session.go b/internal/types/session.go index 34180747..18adb31c 100644 --- a/internal/types/session.go +++ b/internal/types/session.go @@ -79,6 +79,12 @@ type Session struct { Title string `json:"title"` // 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 TenantID uint64 `json:"tenant_id" gorm:"index"` // UserID is the owner of the session. Empty for legacy rows (visible at diff --git a/migrations/versioned/000064_session_external_source.down.sql b/migrations/versioned/000064_session_external_source.down.sql new file mode 100644 index 00000000..45ce2421 --- /dev/null +++ b/migrations/versioned/000064_session_external_source.down.sql @@ -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 $$; diff --git a/migrations/versioned/000064_session_external_source.up.sql b/migrations/versioned/000064_session_external_source.up.sql new file mode 100644 index 00000000..575c5922 --- /dev/null +++ b/migrations/versioned/000064_session_external_source.up.sql @@ -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 $$;