feat(im): IM session improvements — titles, in-flight recovery, classification
Three related improvements to the IM-session experience: - Auto-generated titles: a new IM session starts untitled and gets a content-based title from its first message via the same GenerateTitleAsync flow web sessions use, instead of an identity title like "user · dm". Falls back to the identity title when the first message has no text. All platforms. - In-flight reply recovery (web chat): opening a session whose reply is still being generated on an IM channel made the web client attach via continue-stream and fail (the IM answer never streams through this server), flashing a "stream failed" toast and forcing a manual refresh. Treat a failed attach to an IM reply (channel === 'im') as recoverable — poll until it completes, then reload the thread; on timeout surface the standard error. Web/api replies keep the original behaviour, untouched. - Source-filter classification: the sidebar filter treats "web" as sessions with no IM mapping, but the list join excluded soft-deleted mappings, so /clear'd IM sessions leaked into the user's own web chats. Include soft-deleted mappings so a session ever bound to an IM channel stays under its platform. Adds a repository regression test.
This commit is contained in:
@@ -68,7 +68,7 @@
|
|||||||
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"></botmsg>
|
:isFirstEnter="isFirstEnter" :embeddedMode="embeddedMode"></botmsg>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div v-if="loading"
|
<div v-if="loading || isImRecovering"
|
||||||
style="height: 41px;display: flex;align-items: center;padding-left: 4px;">
|
style="height: 41px;display: flex;align-items: center;padding-left: 4px;">
|
||||||
<div class="loading-typing">
|
<div class="loading-typing">
|
||||||
<span></span>
|
<span></span>
|
||||||
@@ -220,6 +220,16 @@ const limit = ref(20);
|
|||||||
const messagesList = reactive([]);
|
const messagesList = reactive([]);
|
||||||
const isReplying = ref(false);
|
const isReplying = ref(false);
|
||||||
const currentAssistantMessageId = ref(''); // 当前正在生成的 assistant message ID
|
const currentAssistantMessageId = ref(''); // 当前正在生成的 assistant message ID
|
||||||
|
// True only while attaching to an in-flight *IM-originated* reply via continue-stream.
|
||||||
|
// Such replies are generated on the IM side and never stream through this server, so
|
||||||
|
// continue-stream always fails even though the answer is coming — recover by polling
|
||||||
|
// instead of erroring. Web/api replies are left on the original error path.
|
||||||
|
const isAttachingImStream = ref(false);
|
||||||
|
let recoverPollTimer = null;
|
||||||
|
// True while polling to recover an in-flight IM reply we couldn't stream. Drives
|
||||||
|
// the same "generating" typing indicator the normal reply path shows, so the wait
|
||||||
|
// isn't a silent gap. IM-only: false everywhere else, so other flows are unchanged.
|
||||||
|
const isImRecovering = ref(false);
|
||||||
const scrollLock = ref(false);
|
const scrollLock = ref(false);
|
||||||
const isNeedTitle = ref(false);
|
const isNeedTitle = ref(false);
|
||||||
const isFirstEnter = ref(true);
|
const isFirstEnter = ref(true);
|
||||||
@@ -694,7 +704,16 @@ const handleMsgList = async (data, isScrollType = false, newScrollHeight) => {
|
|||||||
currentAssistantMessageId.value = lastMessage.id;
|
currentAssistantMessageId.value = lastMessage.id;
|
||||||
console.log('[Continue Stream] Set assistant message ID:', 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' });
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -832,15 +851,70 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Quietly recover an in-flight IM reply we couldn't attach to (it's generated on
|
||||||
|
// the IM side, so it never streamed through this server). Poll until it completes,
|
||||||
|
// then reload the thread so it renders via the normal path. Bounded so an IM reply
|
||||||
|
// that genuinely died (e.g. the bot crashed) doesn't spin forever — on timeout we
|
||||||
|
// surface the original error so the failure isn't hidden.
|
||||||
|
const RECOVER_POLL_INTERVAL = 2500;
|
||||||
|
const RECOVER_POLL_MAX_ATTEMPTS = 48; // ~2 min
|
||||||
|
const recoverIncompleteMessage = () => {
|
||||||
|
const targetSession = session_id.value;
|
||||||
|
const targetMessageId = currentAssistantMessageId.value;
|
||||||
|
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
|
||||||
|
if (!targetMessageId) { isReplying.value = false; isImRecovering.value = false; return; }
|
||||||
|
isImRecovering.value = true; // show the "generating" indicator while we poll
|
||||||
|
let attempts = 0;
|
||||||
|
const poll = async () => {
|
||||||
|
recoverPollTimer = null;
|
||||||
|
if (session_id.value !== targetSession) { isReplying.value = false; isImRecovering.value = false; return; } // navigated away
|
||||||
|
attempts++;
|
||||||
|
try {
|
||||||
|
const res = await getMessageList({ session_id: targetSession, limit: limit.value, created_at: '' });
|
||||||
|
const target = (res?.data || []).find((m) => m.id === targetMessageId);
|
||||||
|
if (target && target.is_completed) {
|
||||||
|
created_at.value = '';
|
||||||
|
messagesList.splice(0);
|
||||||
|
getmsgList({ session_id: targetSession, limit: limit.value, created_at: '' });
|
||||||
|
isReplying.value = false;
|
||||||
|
isImRecovering.value = false;
|
||||||
|
currentAssistantMessageId.value = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[Continue Stream] recovery poll failed:', e);
|
||||||
|
}
|
||||||
|
if (attempts >= RECOVER_POLL_MAX_ATTEMPTS) {
|
||||||
|
// The IM reply never completed — don't hide it; surface the standard
|
||||||
|
// stream-failure message (reuses the existing i18n key, no raw HTTP code).
|
||||||
|
MessagePlugin.error(t('error.streamFailed'));
|
||||||
|
isReplying.value = false;
|
||||||
|
isImRecovering.value = false;
|
||||||
|
currentAssistantMessageId.value = '';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
recoverPollTimer = setTimeout(poll, RECOVER_POLL_INTERVAL);
|
||||||
|
};
|
||||||
|
recoverPollTimer = setTimeout(poll, RECOVER_POLL_INTERVAL);
|
||||||
|
};
|
||||||
|
|
||||||
// Watch for stream errors and show message
|
// Watch for stream errors and show message
|
||||||
watch(error, (newError) => {
|
watch(error, (newError) => {
|
||||||
if (newError) {
|
if (!newError) return;
|
||||||
MessagePlugin.error(newError);
|
// A failed attach to an in-flight IM reply isn't a real error — the answer is
|
||||||
isReplying.value = false;
|
// produced on the IM side and never streams here. Recover quietly by polling to
|
||||||
loading.value = false;
|
// completion instead of flashing a "stream failed" toast. Web/api replies fall
|
||||||
// 清空当前 assistant message ID
|
// through to the normal error toast below, unchanged.
|
||||||
currentAssistantMessageId.value = '';
|
if (isAttachingImStream.value) {
|
||||||
|
isAttachingImStream.value = false;
|
||||||
|
recoverIncompleteMessage();
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
MessagePlugin.error(newError);
|
||||||
|
isReplying.value = false;
|
||||||
|
loading.value = false;
|
||||||
|
// 清空当前 assistant message ID
|
||||||
|
currentAssistantMessageId.value = '';
|
||||||
});
|
});
|
||||||
|
|
||||||
// 处理流式数据
|
// 处理流式数据
|
||||||
@@ -1574,10 +1648,14 @@ const clearData = () => {
|
|||||||
isReplying.value = false;
|
isReplying.value = false;
|
||||||
fullContent.value = '';
|
fullContent.value = '';
|
||||||
userquery.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(() => {
|
onUnmounted(() => {
|
||||||
window.removeEventListener('session-messages-cleared', handleSessionCleared);
|
window.removeEventListener('session-messages-cleared', handleSessionCleared);
|
||||||
|
if (recoverPollTimer) { clearTimeout(recoverPollTimer); recoverPollTimer = null; }
|
||||||
});
|
});
|
||||||
onBeforeRouteLeave((to, from, next) => {
|
onBeforeRouteLeave((to, from, next) => {
|
||||||
clearData()
|
clearData()
|
||||||
|
|||||||
@@ -136,7 +136,16 @@ func (r *sessionRepository) QueryPaged(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// LEFT JOIN IM mappings to surface origin fields and support source/agent filters.
|
// LEFT JOIN IM mappings to surface origin fields and support source/agent filters.
|
||||||
joinClause := "LEFT JOIN im_channel_sessions ics ON ics.session_id = s.id AND ics.deleted_at IS NULL"
|
// Soft-deleted mappings are intentionally included: a session that was ever bound
|
||||||
|
// to an IM channel belongs to that platform, not "web". /clear and session
|
||||||
|
// recycling soft-delete the mapping (and start a fresh session), so filtering
|
||||||
|
// deleted mappings out here would mis-bucket those past IM conversations into the
|
||||||
|
// user's own web chats ("web" = ics.id IS NULL).
|
||||||
|
// Safe from row fan-out because the IM flow only ever creates a *fresh* session
|
||||||
|
// for a new mapping (never re-maps an existing one), so a session has at most one
|
||||||
|
// mapping row. If that ever changes, this JOIN would need a one-row-per-session
|
||||||
|
// guard (the unique index only constrains active mappings).
|
||||||
|
joinClause := "LEFT JOIN im_channel_sessions ics ON ics.session_id = s.id"
|
||||||
|
|
||||||
applySource := func(db *gorm.DB) *gorm.DB {
|
applySource := func(db *gorm.DB) *gorm.DB {
|
||||||
switch strings.ToLower(strings.TrimSpace(q.Source)) {
|
switch strings.ToLower(strings.TrimSpace(q.Source)) {
|
||||||
|
|||||||
@@ -161,3 +161,64 @@ func TestSessionRepositoryDeleteAllHonorsUserScope(t *testing.T) {
|
|||||||
require.Zero(t, countActiveSessionsForTest(t, db, legacySession.ID))
|
require.Zero(t, countActiveSessionsForTest(t, db, legacySession.ID))
|
||||||
require.EqualValues(t, 1, countActiveSessionsForTest(t, db, otherTenantSession.ID))
|
require.EqualValues(t, 1, countActiveSessionsForTest(t, db, otherTenantSession.ID))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// im_channel_sessions row for QueryPaged source-filter tests. Mirrors the columns
|
||||||
|
// the LEFT JOIN projects; kept local to avoid importing internal/im.
|
||||||
|
type testIMChannelSession struct {
|
||||||
|
ID string `gorm:"primaryKey"`
|
||||||
|
SessionID string
|
||||||
|
Platform string
|
||||||
|
ChatID string
|
||||||
|
ThreadID string
|
||||||
|
UserID string
|
||||||
|
AgentID string
|
||||||
|
IMChannelID string `gorm:"column:im_channel_id"`
|
||||||
|
TenantID uint64
|
||||||
|
DeletedAt gorm.DeletedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
func (testIMChannelSession) TableName() string { return "im_channel_sessions" }
|
||||||
|
|
||||||
|
func listItemIDsForTest(items []*types.SessionListItem) []string {
|
||||||
|
ids := make([]string, 0, len(items))
|
||||||
|
for _, it := range items {
|
||||||
|
ids = append(ids, it.ID)
|
||||||
|
}
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
|
||||||
|
// A /clear (or session recycling) soft-deletes the IM mapping and starts a fresh
|
||||||
|
// session. The old session must stay under its IM platform, not leak into "web"
|
||||||
|
// (which would happen if the source-filter join excluded soft-deleted mappings).
|
||||||
|
func TestSessionRepositoryQueryPagedKeepsClearedIMSessionsOutOfWeb(t *testing.T) {
|
||||||
|
repo, db := newSessionRepositoryForTest(t)
|
||||||
|
require.NoError(t, db.AutoMigrate(&testIMChannelSession{}))
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
web := createSessionForTest(t, db, 1, "alice") // never bound to IM -> web
|
||||||
|
active := createSessionForTest(t, db, 1, "alice") // active IM mapping
|
||||||
|
cleared := createSessionForTest(t, db, 1, "alice") // IM mapping soft-deleted by /clear
|
||||||
|
|
||||||
|
require.NoError(t, db.Create(&testIMChannelSession{
|
||||||
|
ID: "m-active", SessionID: active.ID, Platform: "wecom", TenantID: 1,
|
||||||
|
}).Error)
|
||||||
|
clearedMapping := &testIMChannelSession{
|
||||||
|
ID: "m-cleared", SessionID: cleared.ID, Platform: "wecom", TenantID: 1,
|
||||||
|
}
|
||||||
|
require.NoError(t, db.Create(clearedMapping).Error)
|
||||||
|
require.NoError(t, db.Delete(clearedMapping).Error) // soft-delete, as /clear does
|
||||||
|
|
||||||
|
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),
|
||||||
|
"web must exclude sessions that ever had an IM mapping, including cleared ones")
|
||||||
|
|
||||||
|
wecomItems, _, err := repo.QueryPaged(ctx, &types.SessionListQuery{
|
||||||
|
TenantID: 1, UserID: "alice", Source: "wecom", Page: 1, PageSize: 50,
|
||||||
|
})
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.ElementsMatch(t, []string{active.ID, cleared.ID}, listItemIDsForTest(wecomItems),
|
||||||
|
"wecom must include both the active and the cleared IM session")
|
||||||
|
}
|
||||||
|
|||||||
+32
-4
@@ -1176,6 +1176,16 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Title an untitled IM session from its first text message, like web chats.
|
||||||
|
// GenerateTitleAsync self-guards on a non-empty title and persists to the DB;
|
||||||
|
// nil eventBus is fine (IM has no live stream — the sidebar reloads it).
|
||||||
|
if session.Title == "" && strings.TrimSpace(msg.Content) != "" {
|
||||||
|
// Copy the session: the async title goroutine writes Title while the QA
|
||||||
|
// worker below shares the same *session.
|
||||||
|
sessionForTitle := *session
|
||||||
|
s.sessionService.GenerateTitleAsync(sessionCtx, &sessionForTitle, msg.Content, "", nil)
|
||||||
|
}
|
||||||
|
|
||||||
// 5. Enqueue the QA request into the bounded worker pool.
|
// 5. Enqueue the QA request into the bounded worker pool.
|
||||||
// The worker pool controls LLM concurrency and provides backpressure.
|
// The worker pool controls LLM concurrency and provides backpressure.
|
||||||
qaCtx, qaCancel := context.WithCancel(sessionCtx)
|
qaCtx, qaCancel := context.WithCancel(sessionCtx)
|
||||||
@@ -1480,8 +1490,23 @@ func shortID(id string) string {
|
|||||||
return id
|
return id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// imInitialSessionTitle picks a new IM session's starting title: "" when the
|
||||||
|
// message has text to summarise (so it gets a content-based title later, like
|
||||||
|
// web chats), otherwise the IM identity title so the row is never blank.
|
||||||
|
func imInitialSessionTitle(msg *IncomingMessage, identityTitle func(*IncomingMessage) string) string {
|
||||||
|
if strings.TrimSpace(msg.Content) != "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return identityTitle(msg)
|
||||||
|
}
|
||||||
|
|
||||||
// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id, agent_id).
|
// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id, agent_id).
|
||||||
// This is the original session resolution strategy.
|
// This is the original session resolution strategy.
|
||||||
|
//
|
||||||
|
// Invariant: a cache miss creates a brand-new session — we never attach a second
|
||||||
|
// mapping to an existing session. The session-list source filter (repository
|
||||||
|
// QueryPaged) relies on this one-mapping-per-session property; if this ever
|
||||||
|
// re-maps an existing session, that JOIN needs a one-row-per-session guard.
|
||||||
func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) {
|
||||||
var cs ChannelSession
|
var cs ChannelSession
|
||||||
result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL",
|
result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL",
|
||||||
@@ -1496,8 +1521,10 @@ func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage,
|
|||||||
return nil, fmt.Errorf("query channel session: %w", result.Error)
|
return nil, fmt.Errorf("query channel session: %w", result.Error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create a new WeKnora session
|
// Create a new WeKnora session. Start untitled when there's text to summarise
|
||||||
title := buildUserSessionTitle(msg)
|
// so it gets a content-based title after the first message (see HandleMessage);
|
||||||
|
// fall back to the IM identity title otherwise.
|
||||||
|
title := imInitialSessionTitle(msg, buildUserSessionTitle)
|
||||||
|
|
||||||
newSession := &types.Session{
|
newSession := &types.Session{
|
||||||
TenantID: tenantID,
|
TenantID: tenantID,
|
||||||
@@ -1568,8 +1595,9 @@ func (s *Service) resolveThreadSession(ctx context.Context, msg *IncomingMessage
|
|||||||
return nil, fmt.Errorf("query thread session: %w", result.Error)
|
return nil, fmt.Errorf("query thread session: %w", result.Error)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a session title including chat + thread suffix for traceability.
|
// Start untitled when there's text to summarise so it gets a content-based
|
||||||
title := buildThreadSessionTitle(msg)
|
// title after the first message; fall back to the chat/thread identity title.
|
||||||
|
title := imInitialSessionTitle(msg, buildThreadSessionTitle)
|
||||||
|
|
||||||
newSession := &types.Session{
|
newSession := &types.Session{
|
||||||
TenantID: tenantID,
|
TenantID: tenantID,
|
||||||
|
|||||||
@@ -107,3 +107,49 @@ func TestBuildThreadSessionTitle(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIMInitialSessionTitle(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
msg *IncomingMessage
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "text message starts untitled so it gets a content-based title later",
|
||||||
|
msg: &IncomingMessage{
|
||||||
|
Platform: "feishu",
|
||||||
|
UserName: "李四",
|
||||||
|
ChatType: ChatTypeDirect,
|
||||||
|
Content: "如何配置单点登录?",
|
||||||
|
},
|
||||||
|
want: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "whitespace-only content falls back to the identity title",
|
||||||
|
msg: &IncomingMessage{
|
||||||
|
Platform: "feishu",
|
||||||
|
UserName: "李四",
|
||||||
|
ChatType: ChatTypeDirect,
|
||||||
|
Content: " ",
|
||||||
|
},
|
||||||
|
want: "李四 · dm",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "non-text message (no content) falls back to the identity title",
|
||||||
|
msg: &IncomingMessage{
|
||||||
|
Platform: "wecom",
|
||||||
|
UserID: "WeCom_ZhangSan",
|
||||||
|
ChatType: ChatTypeGroup,
|
||||||
|
ChatID: "wc_group_1234",
|
||||||
|
},
|
||||||
|
want: "user ZhangSan · group oup_1234",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := imInitialSessionTitle(tt.msg, buildUserSessionTitle); got != tt.want {
|
||||||
|
t.Errorf("imInitialSessionTitle() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user