Files
Enterprise-Knowledge-Base/migrations/versioned/000038_im_session_agent_id.down.sql
T
wizardchen c578fdbad6 fix(im): isolate IM sessions per agent and recover from deleted sessions
Three bugs fixed:

1. Session cross-contamination (#1066): resolveUserSession and
   resolveThreadSession looked up ChannelSession by (platform, user_id,
   chat_id, tenant_id) without agent_id. When the same user talked to
   two bots bound to different agents under the same tenant, they shared
   a session — mixing knowledge base context. Add agent_id to all four
   WHERE clauses and update the DB unique indexes to match.

2. Swapped parameters in resolveThreadSession: the SQL expected
   (chat_id, thread_id) but Go args passed (threadID, msg.ChatID).

3. Orphaned ChannelSession crash (#1046): deleting a session from the
   WeKnora UI soft-deletes it (GORM), but the ChannelSession row
   survives because soft-delete doesn't trigger SQL ON DELETE CASCADE.
   Subsequent IM messages hit "record not found" on GetSession and the
   bot becomes permanently unresponsive. Now detect this case, recycle
   the stale mapping, and transparently create a fresh session.
2026-04-28 20:53:06 +08:00

13 lines
483 B
SQL

-- Rollback: 000038_im_session_agent_id
-- Restores the original indexes without agent_id.
DROP INDEX IF EXISTS idx_channel_lookup;
CREATE UNIQUE INDEX idx_channel_lookup
ON im_channel_sessions (platform, user_id, chat_id, tenant_id)
WHERE deleted_at IS NULL;
DROP INDEX IF EXISTS idx_channel_thread_lookup;
CREATE UNIQUE INDEX idx_channel_thread_lookup
ON im_channel_sessions (platform, chat_id, thread_id, tenant_id)
WHERE deleted_at IS NULL AND thread_id != '';