refactor: remove Neo4j-based conversation memory feature

Drop the memory pipeline, API fields, settings UI, and embed toggles so chat no longer depends on Neo4j graph storage for episodic recall.
This commit is contained in:
wizardchen
2026-07-18 23:40:20 +08:00
committed by lyingbug
parent 7807dee42a
commit 380e371c2e
45 changed files with 47 additions and 915 deletions
-2
View File
@@ -26,7 +26,6 @@
| `summary_model_id` | string | 否 | 覆盖默认的摘要模型 ID |
| `mentioned_items` | object[] | 否 | @提及的知识库和文件列表 |
| `disable_title` | bool | 否 | 是否禁用自动标题生成(默认 false) |
| `enable_memory` | bool | 否 | 是否启用记忆功能 |
| `images` | object[] | 否 | 附带的图片(base64 格式),需要 Agent 启用图片上传 |
| `channel` | string | 否 | 来源渠道标识:`web`、`api`、`im`、`browser_extension` |
| `suggestion_attribution` | object | 否 | 用户从推荐问题发起本轮时传入 `{suggestion_set_id, question_id}`;服务端会校验归属 |
@@ -77,7 +76,6 @@ Agent 模式支持更智能的问答,包括工具调用、网络搜索、多
| `summary_model_id` | string | 否 | 覆盖默认的摘要模型 ID |
| `mentioned_items` | object[] | 否 | @提及的知识库和文件列表 |
| `disable_title` | bool | 否 | 是否禁用自动标题生成(默认 false) |
| `enable_memory` | bool | 否 | 是否启用记忆功能 |
| `images` | object[] | 否 | 附带的图片(base64 格式),需要 Agent 启用图片上传 |
| `channel` | string | 否 | 来源渠道标识:`web`、`api`、`im`、`browser_extension` |
| `suggestion_attribution` | object | 否 | 用户从推荐问题发起本轮时传入 `{suggestion_set_id, question_id}`;服务端会校验归属 |
+1 -12
View File
@@ -19050,7 +19050,7 @@ const docTemplate = `{
"type": "boolean"
},
"preferences": {
"description": "Per-user UI/feature preferences (memory toggle, future knobs).\nStored as JSON (jsonb on Postgres, TEXT on SQLite) via the\ndriver.Valuer / sql.Scanner methods on UserPreferences.",
"description": "Per-user UI/feature preferences.\nStored as JSON (jsonb on Postgres, TEXT on SQLite) via the\ndriver.Valuer / sql.Scanner methods on UserPreferences.",
"allOf": [
{
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UserPreferences"
@@ -19120,10 +19120,6 @@ const docTemplate = `{
"github_com_Tencent_WeKnora_internal_types.UserPreferences": {
"type": "object",
"properties": {
"enable_memory": {
"description": "EnableMemory mirrors the \"开启记忆功能\" switch in General Settings.\nnil = preference never set (treat as feature default = false)\n*false / *true = user explicitly set the toggle.",
"type": "boolean"
},
"last_active_tenant_id": {
"description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.",
"type": "integer"
@@ -21560,9 +21556,6 @@ const docTemplate = `{
"internal_handler.updateMyPreferencesRequest": {
"type": "object",
"properties": {
"enable_memory": {
"type": "boolean"
},
"last_active_tenant_id": {
"description": "LastActiveTenantID lets the SPA persist \"after a fresh login,\ndrop me back into this workspace\" across devices. Send a positive\nworkspace id to set / replace, or 0 to clear. Membership is validated\nat next login, not here. Nil = field omitted from the PATCH and\nstays untouched.",
"type": "integer"
@@ -21622,10 +21615,6 @@ const docTemplate = `{
"description": "Whether to disable auto title generation",
"type": "boolean"
},
"enable_memory": {
"description": "EnableMemory is the per-request override for the memory feature.\nPointer + omitempty so the request can distinguish three states:\n nil = client did not specify; backend falls back to the calling\n user's persisted preference (user.preferences.enable_memory),\n defaulting to false if that's also unset. This is the path\n used by the normal logged-in chat UI now that the toggle is\n stored server-side per user.\n *true / *false = explicit override. Embedded mode forces *false so a\n user's personal memory setting doesn't leak into a widget\n context; older clients that still send a literal bool also\n land here (back-compat).",
"type": "boolean"
},
"images": {
"description": "Attached images for multimodal chat",
"type": "array",
+1 -12
View File
@@ -19043,7 +19043,7 @@
"type": "boolean"
},
"preferences": {
"description": "Per-user UI/feature preferences (memory toggle, future knobs).\nStored as JSON (jsonb on Postgres, TEXT on SQLite) via the\ndriver.Valuer / sql.Scanner methods on UserPreferences.",
"description": "Per-user UI/feature preferences.\nStored as JSON (jsonb on Postgres, TEXT on SQLite) via the\ndriver.Valuer / sql.Scanner methods on UserPreferences.",
"allOf": [
{
"$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.UserPreferences"
@@ -19113,10 +19113,6 @@
"github_com_Tencent_WeKnora_internal_types.UserPreferences": {
"type": "object",
"properties": {
"enable_memory": {
"description": "EnableMemory mirrors the \"开启记忆功能\" switch in General Settings.\nnil = preference never set (treat as feature default = false)\n*false / *true = user explicitly set the toggle.",
"type": "boolean"
},
"last_active_tenant_id": {
"description": "LastActiveTenantID remembers the last workspace the user actively\nswitched into, so a fresh login (new device, cleared browser, new\nrefresh token) lands them back in that workspace instead of always\nbouncing to their home workspace. Login / RefreshToken validate that\nthe workspace still exists and the user still has an active membership\n(or CanAccessAllTenants) before honouring this preference; an\ninvalid pointer is best-effort cleared and the user falls back to\nhome.\n\nnil = no preference (use user.TenantID, i.e. home)\n*0 = \"clear preference\" sentinel for the partial-update endpoint\n (UpdateUserPreferences turns this into nil). Otherwise treat\n a stored *0 the same as nil.\n*N = preferred workspace id.",
"type": "integer"
@@ -21553,9 +21549,6 @@
"internal_handler.updateMyPreferencesRequest": {
"type": "object",
"properties": {
"enable_memory": {
"type": "boolean"
},
"last_active_tenant_id": {
"description": "LastActiveTenantID lets the SPA persist \"after a fresh login,\ndrop me back into this workspace\" across devices. Send a positive\nworkspace id to set / replace, or 0 to clear. Membership is validated\nat next login, not here. Nil = field omitted from the PATCH and\nstays untouched.",
"type": "integer"
@@ -21615,10 +21608,6 @@
"description": "Whether to disable auto title generation",
"type": "boolean"
},
"enable_memory": {
"description": "EnableMemory is the per-request override for the memory feature.\nPointer + omitempty so the request can distinguish three states:\n nil = client did not specify; backend falls back to the calling\n user's persisted preference (user.preferences.enable_memory),\n defaulting to false if that's also unset. This is the path\n used by the normal logged-in chat UI now that the toggle is\n stored server-side per user.\n *true / *false = explicit override. Embedded mode forces *false so a\n user's personal memory setting doesn't leak into a widget\n context; older clients that still send a literal bool also\n land here (back-compat).",
"type": "boolean"
},
"images": {
"description": "Attached images for multimodal chat",
"type": "array",
+1 -23
View File
@@ -3608,7 +3608,7 @@ definitions:
allOf:
- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.UserPreferences'
description: |-
Per-user UI/feature preferences (memory toggle, future knobs).
Per-user UI/feature preferences.
Stored as JSON (jsonb on Postgres, TEXT on SQLite) via the
driver.Valuer / sql.Scanner methods on UserPreferences.
tenant:
@@ -3652,12 +3652,6 @@ definitions:
type: object
github_com_Tencent_WeKnora_internal_types.UserPreferences:
properties:
enable_memory:
description: |-
EnableMemory mirrors the "开启记忆功能" switch in General Settings.
nil = preference never set (treat as feature default = false)
*false / *true = user explicitly set the toggle.
type: boolean
last_active_tenant_id:
description: |-
LastActiveTenantID remembers the last workspace the user actively
@@ -5435,8 +5429,6 @@ definitions:
type: object
internal_handler.updateMyPreferencesRequest:
properties:
enable_memory:
type: boolean
last_active_tenant_id:
description: |-
LastActiveTenantID lets the SPA persist "after a fresh login,
@@ -5483,20 +5475,6 @@ definitions:
disable_title:
description: Whether to disable auto title generation
type: boolean
enable_memory:
description: |-
EnableMemory is the per-request override for the memory feature.
Pointer + omitempty so the request can distinguish three states:
nil = client did not specify; backend falls back to the calling
user's persisted preference (user.preferences.enable_memory),
defaulting to false if that's also unset. This is the path
used by the normal logged-in chat UI now that the toggle is
stored server-side per user.
*true / *false = explicit override. Embedded mode forces *false so a
user's personal memory setting doesn't leak into a widget
context; older clients that still send a literal bool also
land here (back-compat).
type: boolean
images:
description: Attached images for multimodal chat
items:
-1
View File
@@ -95,7 +95,6 @@ export interface RegisterResponse {
// 新加 key 时记得:后端 service.UpdateUserPreferences 也要在 merge 分支里
// 处理;前端调用方按需读 / 默认值降级。
export interface UserPreferences {
enable_memory?: boolean
// last_active_tenant_id 持久化「刷新 / 换设备 / 重新登录后回到上次的空间」
// 偏好;后端在 Login / RefreshToken 时校验 membership 有效后才会沿用,
// 否则回退到 home 并清掉这个字段。传 0 给 PATCH 表示「清除偏好」。
+1 -5
View File
@@ -36,7 +36,7 @@ export function useStream() {
let renderTimer: number | null = null
// 启动流式请求
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; tag_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; skill_names?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string; kb_id?: string; kb_name?: string; service_id?: string; skill_name?: string}>; images?: Array<{data: string}>; attachment_uploads?: Array<{data: string; file_name: string; file_size: number}>; attachment_ids?: string[]; suggestion_attribution?: { suggestion_set_id: string; question_id: string }; method: string; url: string; embed_token?: string; embed_session_sig?: string; embed_visitor_id?: string }) => {
const myGeneration = ++streamGeneration
// 重置状态
output.value = '';
@@ -103,10 +103,6 @@ export function useStream() {
if (params.web_search_enabled !== undefined) {
postBody.web_search_enabled = params.web_search_enabled;
}
// Include enable_memory if provided
if (params.enable_memory !== undefined) {
postBody.enable_memory = params.enable_memory;
}
// Include summary_model_id if provided (for non-Agent mode)
if (params.summary_model_id) {
postBody.summary_model_id = params.summary_model_id;
-2
View File
@@ -17,7 +17,6 @@ export interface EmbedChannel {
show_suggested_questions?: boolean
widget_position?: WidgetPosition
allow_web_search?: boolean
allow_memory?: boolean
allow_file_upload?: boolean
default_locale?: string
webhook_url?: string
@@ -42,7 +41,6 @@ export interface EmbedChannelPublicConfig {
show_suggested_questions?: boolean
widget_position?: WidgetPosition
allow_web_search?: boolean
allow_memory?: boolean
allow_file_upload?: boolean
agent_web_search_enabled?: boolean
agent_image_upload_enabled?: boolean
@@ -312,7 +312,6 @@ export function useEmbedChatSession(options: {
agent_enabled: agentEnabled,
agent_id: options.agentId,
web_search_enabled: (options.allowWebSearch ?? false) && visitorWebSearchEnabled,
enable_memory: false,
summary_model_id: '',
mcp_service_ids: [],
mentioned_items: [],
-6
View File
@@ -1240,12 +1240,8 @@ export default {
conversationConfig: 'Conversation Settings',
conversationStrategy: 'Conversation Strategy',
webSearchConfig: 'Web Search',
enableMemory: 'Enable Memory',
enableMemoryDesc: 'When enabled, the system will record your conversation history and automatically recall relevant content in future conversations to provide more personalized answers.',
autoCheckUpdate: 'Auto Download Updates',
autoCheckUpdateDesc: 'When enabled, automatically check and download the latest version in the background.',
memoryRequiresNeo4j: 'Memory feature requires Neo4j graph database. Please configure and enable Neo4j (set NEO4J_ENABLE=true) before enabling this feature.',
memoryHowToEnable: 'View Neo4j Configuration Guide',
vectorStoreEngine: 'Vector DB Engine',
parserEngine: 'Parser Engine',
storageEngine: 'Storage Engine',
@@ -2553,8 +2549,6 @@ export default {
sectionCapabilities: 'Chat capabilities',
allowWebSearch: 'Show web search toggle',
allowWebSearchDesc: 'When enabled, visitors see a web search button in the input area and can turn it on or off themselves; it stays off by default. The button appears only if the bound agent has web search enabled.',
allowMemory: 'Allow memory',
allowMemoryDesc: 'When enabled, anonymous visitors retain context within the same session; memory is lost when they clear browser data or start a new chat. Off by default.',
allowFileUpload: 'Show file upload',
allowFileUploadDesc: 'When enabled, visitors can upload images and document attachments. Requires the bound agent to support image upload.',
webhookUrl: 'Webhook URL',
-6
View File
@@ -1105,12 +1105,8 @@ export default {
conversationConfig: "대화 설정",
conversationStrategy: "대화 전략",
webSearchConfig: "웹 검색",
enableMemory: "기억 기능 활성화",
enableMemoryDesc: "활성화하면 시스템이 대화 기록을 저장하고 향후 대화에서 관련 내용을 자동으로 회상하여 더 개인화된 답변을 제공합니다.",
autoCheckUpdate: '업데이트 자동 다운로드',
autoCheckUpdateDesc: '활성화하면 시작 시 최신 버전을 자동으로 확인하고 백그라운드에서 다운로드합니다.',
memoryRequiresNeo4j: "기억 기능은 Neo4j 그래프 데이터베이스가 필요합니다. 이 기능을 활성화하기 전에 Neo4j를 구성하고 활성화해 주세요 (NEO4J_ENABLE=true 설정).",
memoryHowToEnable: "Neo4j 구성 가이드 보기",
vectorStoreEngine: "벡터 DB 엔진",
parserEngine: "파싱 엔진",
storageEngine: "스토리지 엔진",
@@ -3775,8 +3771,6 @@ export default {
sectionCapabilities: '대화 기능',
allowWebSearch: '웹 검색 토글 표시',
allowWebSearchDesc: '활성화하면 방문자 입력창에 웹 검색 버튼이 표시되며, 방문자가 직접 켜거나 끌 수 있습니다. 기본값은 꺼짐입니다. 연결된 에이전트에서 웹 검색이 활성화된 경우에만 버튼이 나타납니다.',
allowMemory: '메모리 허용',
allowMemoryDesc: '활성화하면 익명 방문자가 동일 세션 내에서 컨텍스트를 유지합니다. 브라우저 데이터 삭제 또는 새 대화 시작 시 메모리가 사라집니다. 기본값은 꺼짐.',
allowFileUpload: '이미지 업로드 버튼 표시',
allowFileUploadDesc: '활성화하면 방문자 입력창에 이미지 업로드 버튼이 표시됩니다. 연결된 에이전트에서 이미지 업로드가 활성화된 경우에만 버튼이 나타납니다.',
agentWebSearchDisabledHint: '현재 에이전트에서 웹 검색이 활성화되지 않았습니다. 방문자에게 웹 검색 버튼이 표시되지 않습니다. 에이전트 설정에서 웹 검색을 먼저 활성화하세요.',
-6
View File
@@ -1151,12 +1151,8 @@ export default {
modelManagement: 'Управление моделями',
agentConfig: 'Настройки агента',
webSearchConfig: 'Сетевой поиск',
enableMemory: 'Включить память',
enableMemoryDesc: 'При включении система будет записывать историю ваших разговоров и автоматически вспоминать соответствующий контент в будущих беседах для более персонализированных ответов.',
autoCheckUpdate: 'Автоматическая загрузка обновлений',
autoCheckUpdateDesc: 'При включении автоматически проверять и скачивать последнюю версию в фоновом режиме при запуске.',
memoryRequiresNeo4j: 'Функция памяти требует графовую базу данных Neo4j. Пожалуйста, настройте и включите Neo4j (установите NEO4J_ENABLE=true) перед активацией этой функции.',
memoryHowToEnable: 'Руководство по настройке Neo4j',
vectorStoreEngine: 'Движок векторной БД',
parserEngine: 'Движок парсинга',
storageEngine: 'Движок хранения',
@@ -3249,8 +3245,6 @@ export default {
sectionCapabilities: 'Возможности чата',
allowWebSearch: 'Показывать переключатель веб-поиска',
allowWebSearchDesc: 'При включении посетители видят кнопку веб-поиска в поле ввода и могут включать или выключать его сами; по умолчанию выключен. Кнопка появляется только если у привязанного агента включён веб-поиск.',
allowMemory: 'Разрешить память',
allowMemoryDesc: 'При включении анонимные посетители сохраняют контекст в рамках одной сессии; память теряется при очистке данных браузера или новом чате. По умолчанию выключено.',
allowFileUpload: 'Показывать кнопку загрузки изображений',
allowFileUploadDesc: 'При включении посетители видят кнопку загрузки изображений в поле ввода. Кнопка появляется только если у привязанного агента включена загрузка изображений.',
agentWebSearchDisabledHint: 'У этого агента не включён веб-поиск. Посетители не увидят кнопку веб-поиска, пока вы не включите его в настройках агента.',
-6
View File
@@ -1113,12 +1113,8 @@ export default {
conversationConfig: "对话设置",
conversationStrategy: "对话策略",
webSearchConfig: "网络搜索",
enableMemory: "开启记忆功能",
enableMemoryDesc: "开启后,系统将记录您的对话历史,并在后续对话中自动回忆相关内容,提供更个性化的回答。",
autoCheckUpdate: '自动下载更新',
autoCheckUpdateDesc: '开启后自动检查并在后台下载最新版本安装包。',
memoryRequiresNeo4j: "记忆功能依赖 Neo4j 图数据库,请先配置并启用 Neo4j(设置环境变量 NEO4J_ENABLE=true)后再开启此功能。",
memoryHowToEnable: "查看 Neo4j 配置指南",
vectorStoreEngine: "向量数据库引擎",
parserEngine: "解析引擎",
storageEngine: "存储引擎",
@@ -3796,8 +3792,6 @@ export default {
sectionCapabilities: "对话能力",
allowWebSearch: "显示联网搜索开关",
allowWebSearchDesc: "开启后,访客输入框会显示联网搜索按钮,可自行打开或关闭;不会默认开启。仅当绑定的智能体已启用联网搜索时按钮才会出现。",
allowMemory: "允许记忆",
allowMemoryDesc: "开启后,匿名访客可在同一会话内保留上下文记忆;访客清除浏览器数据或新建对话后记忆会丢失。默认关闭。",
allowFileUpload: "显示文件上传",
allowFileUploadDesc: "开启后,访客可上传图片与文档附件。仅当绑定的智能体已启用图片上传时才会生效。",
webhookUrl: "Webhook 地址",
-11
View File
@@ -192,17 +192,6 @@ export const useAuthStore = defineStore('auth', () => {
if (previousId !== userData.id) {
reloadUserPreferences()
}
// 把后端持久化的 user 偏好(记忆开关等)同步到 settings store。
// 用 import 而不是顶部 import 避免 stores 间的循环依赖:auth ↔ settings。
// settings store 只把它当作"本地状态 + localStorage"更新,不会再原路 PUT 回去。
if (userData.preferences) {
import('@/stores/settings').then(({ useSettingsStore }) => {
useSettingsStore().hydrateFromUserPreferences(userData.preferences)
}).catch(() => {
// 加载 settings store 失败不影响 setUser 主流程;下次 setUser
// 触发时还会再次尝试同步。
})
}
}
const setTenant = (tenantData: TenantInfo | null) => {
-47
View File
@@ -2,7 +2,6 @@ import { defineStore } from "pinia";
import { nextTick } from "vue";
import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";
import { getApiBaseUrl } from "@/utils/api-base";
import { updateMyPreferences, type UserPreferences } from "@/api/auth";
import { isAgentStreamAgentId } from "@/utils/agent-mode";
import { loadAndReconcileSettings } from "@/stores/settingsStorage";
@@ -23,7 +22,6 @@ interface Settings {
modelConfig: ModelConfig; // 模型配置
ollamaConfig: OllamaConfig; // Ollama配置
webSearchEnabled: boolean; // 网络搜索是否启用
enableMemory: boolean; // 是否开启记忆功能
conversationModels: ConversationModels;
selectedAgentId: string; // 当前选中的智能体ID
selectedAgentSourceTenantId: string | null; // 当使用共享智能体时,来源空间 ID(用于后端 model/KB/MCP 解析)
@@ -100,7 +98,6 @@ const defaultSettings: Settings = {
enabled: true
},
webSearchEnabled: false, // 默认关闭网络搜索
enableMemory: false, // 默认关闭记忆功能
conversationModels: {
summaryModelId: "",
rerankModelId: "",
@@ -170,9 +167,6 @@ export const useSettingsStore = defineStore("settings", {
// 网络搜索是否启用
isWebSearchEnabled: (state) => state.settings.webSearchEnabled || false,
// 记忆功能是否启用
isMemoryEnabled: (state) => state.settings.enableMemory || false,
// 是否自动检查并下载更新
isAutoCheckUpdateEnabled: (state) => state.settings.autoCheckUpdate ?? true,
@@ -334,47 +328,6 @@ export const useSettingsStore = defineStore("settings", {
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
},
// 启用/禁用记忆功能。
// 现在是"真用户级"开关:
// - 本地缓存 (localStorage) 用作 UI 首屏 / 离线兜底;
// - PUT /auth/me/preferences 是真正的持久化,跨设备/浏览器同步。
//
// 乐观更新:先翻本地状态让 UI 立刻响应,再异步写后端;失败则回滚 + throw
// 让调用方(GeneralSettings.vue 的 t-switch)可以提示并把开关复位。
async toggleMemory(enabled: boolean): Promise<void> {
const previous = !!this.settings.enableMemory;
this.settings.enableMemory = enabled;
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
try {
const resp = await updateMyPreferences({ enable_memory: enabled });
if (!resp.success) {
throw new Error(resp.message || "update failed");
}
} catch (err) {
// 回滚本地状态,让 UI 复位到旧值。
this.settings.enableMemory = previous;
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
throw err;
}
},
// 从 /auth/me 或 /auth/login 返回的 user.preferences 同步到本地 settings。
// 调用方:authStore.setUser(每次登录 / 刷新 user / 切空间后都会触发)。
// 不写后端,纯本地状态 + localStorage 写入,避免把后端的值再原路 PUT 回去。
hydrateFromUserPreferences(prefs: UserPreferences | undefined | null) {
if (!prefs) return;
let changed = false;
if (typeof prefs.enable_memory === "boolean" &&
this.settings.enableMemory !== prefs.enable_memory) {
this.settings.enableMemory = prefs.enable_memory;
changed = true;
}
if (changed) {
localStorage.setItem("WeKnora_settings", JSON.stringify(this.settings));
}
},
// 启用/禁用自动检查更新
toggleAutoCheckUpdate(enabled: boolean) {
this.settings.autoCheckUpdate = enabled;
+7 -1
View File
@@ -20,6 +20,7 @@ type ReconcilableSettings = {
selectedSkills?: unknown;
selectedTools?: unknown;
selectedFileKbMap?: unknown;
enableMemory?: unknown;
isAgentEnabled: boolean;
selectedAgentId?: string;
};
@@ -29,7 +30,12 @@ function reconcileLoadedSettings<T extends ReconcilableSettings>(loaded: T): T {
loaded.selectedMCPServices ||= [];
loaded.selectedSkills ||= (loaded.selectedTools as string[] | undefined) || [];
loaded.selectedFileKbMap ||= {};
if (reconcileBuiltinAgentMode(loaded)) {
const removedLegacyMemorySetting = Object.prototype.hasOwnProperty.call(loaded, "enableMemory");
if (removedLegacyMemorySetting) {
delete loaded.enableMemory;
}
const reconciledAgentMode = reconcileBuiltinAgentMode(loaded);
if (removedLegacyMemorySetting || reconciledAgentMode) {
safeSetItem(SETTINGS_STORAGE_KEY, JSON.stringify(loaded));
}
return loaded;
-8
View File
@@ -781,13 +781,6 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
// Get web search status from settings store
const webSearchEnabled = props.embeddedMode ? false : useSettingsStoreInstance.isWebSearchEnabled;
// Memory toggle is now a server-side per-user preference (see PUT
// /auth/me/preferences). For the normal logged-in chat we leave the
// field unset so the backend reads `user.preferences.enable_memory`;
// for embedded widgets we still send an explicit `false` so a user's
// personal "memory on" setting doesn't leak into a KB-embed context.
const enableMemoryOverride = props.embeddedMode ? false : undefined;
// Get knowledge_base_ids from settings store (selected by user via KnowledgeBaseSelector)
// Merge @mentioned KB/file IDs so retrieval uses the same targets user @mentioned (including shared KBs)
const sidebarKbIds = props.embeddedMode ? props.kbIds : (useSettingsStoreInstance.settings.selectedKnowledgeBases || []);
@@ -826,7 +819,6 @@ const sendMsg = async (value, modelId = '', mentionedItems = [], imageFiles = []
agent_enabled: agentEnabled,
agent_id: selectedAgentId,
web_search_enabled: webSearchEnabled,
enable_memory: enableMemoryOverride,
summary_model_id: modelId,
mcp_service_ids: requestMcpServiceIds,
skill_names: requestSkillNames,
@@ -121,34 +121,6 @@
</div>
</div>
<!-- 记忆功能开关 -->
<div class="setting-row">
<div class="setting-info">
<label>{{ $t('settings.enableMemory') }}</label>
<p class="desc">{{ $t('settings.enableMemoryDesc') }}</p>
</div>
<div class="setting-control">
<t-switch
:value="isMemoryEnabled"
:disabled="!isNeo4jAvailable || memorySaving"
:loading="memorySaving"
@change="handleMemoryChange"
/>
</div>
</div>
<t-alert
v-if="!isNeo4jAvailable"
theme="warning"
style="margin-top: -8px; margin-bottom: 16px;"
>
<template #message>
<div>{{ $t('settings.memoryRequiresNeo4j') }}</div>
<t-link theme="primary" href="https://github.com/Tencent/WeKnora/blob/main/docs/KnowledgeGraph.md" target="_blank">
{{ $t('settings.memoryHowToEnable') }}
</t-link>
</template>
</t-alert>
<!-- 自动下载更新开关 (Lite edition only) -->
<div class="setting-row" v-if="authStore.isLiteMode">
<div class="setting-info">
@@ -171,7 +143,6 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { useSettingsStore } from '@/stores/settings'
import { useAuthStore } from '@/stores/auth'
import { getSystemInfo } from '@/api/system'
import { useTheme, type ThemeMode } from '@/composables/useTheme'
import {
useFont,
@@ -232,18 +203,6 @@ const monoFontOptions = computed<{ value: MonoFontKey; label: string; preview: s
const currentSansStack = computed(() => SANS_STACKS[localSansFont.value] ?? SANS_STACKS.system)
const currentMonoStack = computed(() => MONO_STACKS[localMonoFont.value] ?? MONO_STACKS.system)
// 系统信息
const systemInfo = ref<any>(null)
const isNeo4jAvailable = computed(() => {
return systemInfo.value?.graph_database_engine && systemInfo.value.graph_database_engine !== '未启用'
})
// 记忆功能状态:只读 computed(toggleMemory 现在是 async + 后端持久化,
// 触发路径统一走 @change → handleMemoryChange,避免 v-model setter 二次调用)。
const isMemoryEnabled = computed(() => settingsStore.isMemoryEnabled)
const memorySaving = ref(false)
// 自动检查更新状态
const isAutoCheckUpdateEnabled = computed({
get: () => settingsStore.isAutoCheckUpdateEnabled,
@@ -260,7 +219,7 @@ const isAutoCheckUpdateEnabled = computed({
})
// 初始化加载
onMounted(async () => {
onMounted(() => {
// 从 localStorage 加载语言设置
const savedLocale = localStorage.getItem('locale')
if (savedLocale) {
@@ -269,18 +228,6 @@ onMounted(async () => {
} else {
localLanguage.value = locale.value
}
// 加载系统信息以检查 Neo4j 可用性
try {
const response = await getSystemInfo()
systemInfo.value = response.data
if (!isNeo4jAvailable.value && settingsStore.isMemoryEnabled) {
// Neo4j 不可用 → 兜底关掉。后端写入失败不打断主流程(页面级 best-effort)。
void settingsStore.toggleMemory(false).catch(() => {})
}
} catch (error) {
console.error('Failed to load system info:', error)
}
})
// 处理语言变化
@@ -290,25 +237,6 @@ const handleLanguageChange = () => {
MessagePlugin.success(t('language.languageSaved'))
}
// 处理记忆功能变化。
// toggleMemory 是 async:先乐观写本地、再 PUT 后端;失败会回滚并 throw。
// UI 在 saving 期间禁用开关 + 显示 loading,避免用户在请求未完成时反复点。
const handleMemoryChange = async (val: boolean) => {
if (val && !isNeo4jAvailable.value) {
MessagePlugin.warning(t('settings.memoryRequiresNeo4j'))
return
}
memorySaving.value = true
try {
await settingsStore.toggleMemory(val)
MessagePlugin.success(t('common.success'))
} catch (err: any) {
MessagePlugin.error(err?.message || t('error.auth.updatePreferencesFailed'))
} finally {
memorySaving.value = false
}
}
// 处理主题变化
const handleThemeChange = (val: ThemeMode) => {
if (!setTheme(val)) {
@@ -444,4 +372,4 @@ const handleFontSizeChange = (val: FontSizeKey) => {
text-overflow: ellipsis;
}
}
</style>
</style>
@@ -1,148 +0,0 @@
package neo4j
import (
"context"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
)
type MemoryRepository struct {
driver neo4j.Driver
}
func NewMemoryRepository(driver neo4j.Driver) interfaces.MemoryRepository {
return &MemoryRepository{driver: driver}
}
func (r *MemoryRepository) IsAvailable(ctx context.Context) bool {
return r.driver != nil
}
func (r *MemoryRepository) SaveEpisode(ctx context.Context, episode *types.Episode, entities []*types.Entity, relations []*types.Relationship) error {
session := r.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeWrite})
defer session.Close(ctx)
_, err := session.ExecuteWrite(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
// 1. Create Episode Node
createEpisodeQuery := `
MERGE (e:Episode {id: $id})
SET e.user_id = $user_id,
e.session_id = $session_id,
e.summary = $summary,
e.created_at = $created_at
`
_, err := tx.Run(ctx, createEpisodeQuery, map[string]interface{}{
"id": episode.ID,
"user_id": episode.UserID,
"session_id": episode.SessionID,
"summary": episode.Summary,
"created_at": episode.CreatedAt.Format(time.RFC3339),
})
if err != nil {
return nil, fmt.Errorf("failed to create episode: %v", err)
}
// 2. Create Entity Nodes and MENTIONS relationships
for _, entity := range entities {
createEntityQuery := `
MERGE (n:Entity {name: $name})
SET n.type = $type,
n.description = $description
WITH n
MATCH (e:Episode {id: $episode_id})
MERGE (e)-[:MENTIONS]->(n)
`
_, err := tx.Run(ctx, createEntityQuery, map[string]interface{}{
"name": entity.Title,
"type": entity.Type,
"description": entity.Description,
"episode_id": episode.ID,
})
if err != nil {
return nil, fmt.Errorf("failed to create entity %s: %v", entity.Title, err)
}
}
// 3. Create Relationships between Entities
for _, rel := range relations {
createRelQuery := `
MATCH (s:Entity {name: $source})
MATCH (t:Entity {name: $target})
MERGE (s)-[r:RELATED_TO {description: $description}]->(t)
SET r.weight = $weight
`
_, err := tx.Run(ctx, createRelQuery, map[string]interface{}{
"source": rel.Source,
"target": rel.Target,
"description": rel.Description,
"weight": rel.Weight,
})
if err != nil {
return nil, fmt.Errorf("failed to create relationship between %s and %s: %v", rel.Source, rel.Target, err)
}
}
return nil, nil
})
if err != nil {
logger.Errorf(ctx, "failed to save episode: %v", err)
return err
}
return nil
}
func (r *MemoryRepository) FindRelatedEpisodes(ctx context.Context, userID string, keywords []string, limit int) ([]*types.Episode, error) {
session := r.driver.NewSession(ctx, neo4j.SessionConfig{AccessMode: neo4j.AccessModeRead})
defer session.Close(ctx)
result, err := session.ExecuteRead(ctx, func(tx neo4j.ManagedTransaction) (interface{}, error) {
querySimple := `
MATCH (e:Episode)-[:MENTIONS]->(n:Entity)
WHERE e.user_id = $user_id AND n.name IN $keywords
RETURN DISTINCT e
ORDER BY e.created_at DESC
LIMIT $limit
`
res, err := tx.Run(ctx, querySimple, map[string]interface{}{
"user_id": userID,
"keywords": keywords,
"limit": limit,
})
if err != nil {
return nil, err
}
var episodes []*types.Episode
for res.Next(ctx) {
record := res.Record()
node, _ := record.Get("e")
episodeNode := node.(neo4j.Node)
createdAtStr := episodeNode.Props["created_at"].(string)
createdAt, _ := time.Parse(time.RFC3339, createdAtStr)
episodes = append(episodes, &types.Episode{
ID: episodeNode.Props["id"].(string),
UserID: episodeNode.Props["user_id"].(string),
SessionID: episodeNode.Props["session_id"].(string),
Summary: episodeNode.Props["summary"].(string),
CreatedAt: createdAt,
})
}
return episodes, nil
})
if err != nil {
return nil, err
}
return result.([]*types.Episode), nil
}
@@ -1,154 +0,0 @@
package chatpipeline
import (
"context"
"fmt"
"sync"
"github.com/Tencent/WeKnora/internal/event"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
)
type MemoryPlugin struct {
memoryService interfaces.MemoryService
}
func NewMemoryPlugin(eventManager *EventManager, memoryService interfaces.MemoryService) *MemoryPlugin {
res := &MemoryPlugin{
memoryService: memoryService,
}
eventManager.Register(res)
return res
}
func (p *MemoryPlugin) ActivationEvents() []types.EventType {
return []types.EventType{
types.MEMORY_RETRIEVAL,
types.MEMORY_STORAGE,
}
}
func (p *MemoryPlugin) OnEvent(
ctx context.Context,
eventType types.EventType,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
switch eventType {
case types.MEMORY_RETRIEVAL:
return p.handleRetrieval(ctx, chatManage, next)
case types.MEMORY_STORAGE:
return p.handleStorage(ctx, chatManage, next)
default:
return next()
}
}
func (p *MemoryPlugin) handleRetrieval(
ctx context.Context,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
// Check if memory is enabled
if !chatManage.EnableMemory {
return next()
}
logger.Info(ctx, "Start to retrieve memory")
// Retrieve memory context
query := chatManage.RewriteQuery
if query == "" {
query = chatManage.Query
}
memoryContext, err := p.memoryService.RetrieveMemory(ctx, chatManage.UserID, query)
if err != nil {
logger.Errorf(ctx, "failed to retrieve memory: %v", err)
// Don't block the pipeline if memory retrieval fails
return next()
}
// Add memory context to chatManage
if len(memoryContext.RelatedEpisodes) > 0 {
memoryStr := "\n\nRelevant Memory:\n"
for _, ep := range memoryContext.RelatedEpisodes {
memoryStr += fmt.Sprintf("- %s (Summary: %s)\n", ep.CreatedAt.Format("2006-01-02"), ep.Summary)
}
chatManage.UserContent += memoryStr
logger.Infof(ctx, "Retrieved memory: %s", memoryStr)
}
logger.Info(ctx, "End to retrieve memory")
return next()
}
func (p *MemoryPlugin) handleStorage(
ctx context.Context,
chatManage *types.ChatManage,
next func() *PluginError,
) *PluginError {
if err := next(); err != nil {
return err
}
// Check if memory is enabled
if !chatManage.EnableMemory {
return nil
}
logger.Info(ctx, "Start to store memory")
// If ChatResponse is already available (non-streaming), store it directly
if chatManage.ChatResponse != nil {
messages := []types.Message{
{Role: "user", Content: chatManage.Query},
{Role: "assistant", Content: chatManage.ChatResponse.Content},
}
userID := chatManage.UserID
sessionID := chatManage.SessionID
bgCtx := context.WithoutCancel(ctx)
go func() {
if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil {
logger.Errorf(bgCtx, "failed to add episode: %v", err)
}
}()
return nil
}
// If streaming, subscribe to events
if chatManage.EventBus != nil {
var fullResponse string
var storeOnce sync.Once
userID := chatManage.UserID
sessionID := chatManage.SessionID
bgCtx := context.WithoutCancel(ctx)
chatManage.EventBus.On(types.EventType(event.EventAgentFinalAnswer), func(_ context.Context, evt types.Event) error {
data, ok := evt.Data.(event.AgentFinalAnswerData)
if !ok {
return nil
}
fullResponse += data.Content
if data.Done {
// Stream layer may emit Done:true twice (e.g. finish_reason chunk + EOF sentinel).
// qa.go dedupes with completionHandled; keep memory writes consistent with one episode only.
storeOnce.Do(func() {
messages := []types.Message{
{Role: "user", Content: chatManage.Query},
{Role: "assistant", Content: fullResponse},
}
go func() {
if err := p.memoryService.AddEpisode(bgCtx, userID, sessionID, messages); err != nil {
logger.Errorf(bgCtx, "failed to add episode: %v", err)
}
}()
})
}
return nil
})
}
logger.Info(ctx, "End to store memory")
return nil
}
@@ -85,7 +85,6 @@ func (s *embedChannelService) Create(
ShowSuggestedQuestions: req.ShowSuggestedQuestions,
WidgetPosition: types.NormalizeEmbedWidgetPosition(req.WidgetPosition),
AllowWebSearch: req.AllowWebSearch,
AllowMemory: req.AllowMemory,
AllowFileUpload: req.AllowFileUpload,
DefaultLocale: types.NormalizeEmbedDefaultLocale(req.DefaultLocale),
}
@@ -119,7 +118,7 @@ func (s *embedChannelService) ListByTenant(
func (s *embedChannelService) Update(
ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel,
enabled *bool, showSuggested *bool, allowWebSearch *bool, allowMemory *bool, allowFileUpload *bool,
enabled *bool, showSuggested *bool, allowWebSearch *bool, allowFileUpload *bool,
defaultLocale *string, webhookURL *string, webhookSecret *string,
) (*types.EmbedChannel, error) {
ch, err := s.getOwned(ctx, tenantID, id)
@@ -139,9 +138,6 @@ func (s *embedChannelService) Update(
if allowWebSearch != nil {
ch.AllowWebSearch = *allowWebSearch
}
if allowMemory != nil {
ch.AllowMemory = *allowMemory
}
if allowFileUpload != nil {
ch.AllowFileUpload = *allowFileUpload
}
@@ -262,7 +258,6 @@ func (s *embedChannelService) PublicConfig(ctx context.Context, ch *types.EmbedC
AllowedOrigins: ch.AllowedOriginsList(),
WidgetPosition: types.NormalizeEmbedWidgetPosition(ch.WidgetPosition),
AllowWebSearch: ch.AllowWebSearch,
AllowMemory: ch.AllowMemory,
AllowFileUpload: ch.AllowFileUpload,
AgentWebSearchEnabled: agentWebSearchEnabled,
AgentImageUploadEnabled: agentImageUploadEnabled,
@@ -101,15 +101,11 @@ func TestPublicConfigIncludesCapabilityFlags(t *testing.T) {
ID: "ch-cap",
AgentID: "agent-cap",
AllowWebSearch: true,
AllowMemory: true,
WidgetPosition: "top-left",
})
if !cfg.AllowWebSearch {
t.Fatalf("allow_web_search = false, want true")
}
if !cfg.AllowMemory {
t.Fatalf("allow_memory = false, want true")
}
if !cfg.AgentWebSearchEnabled {
t.Fatalf("agent_web_search_enabled = false, want true")
}
@@ -48,7 +48,7 @@ func TestEmbedChannelUpdateAgentID(t *testing.T) {
42,
"ch-1",
&types.EmbedChannel{AgentID: "agent-new"},
&enabled, nil, nil, nil, nil, nil, nil, nil,
&enabled, nil, nil, nil, nil, nil, nil,
)
if err != nil {
t.Fatalf("Update() error = %v", err)
@@ -1,187 +0,0 @@
package memory
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
)
// MemoryService implements the MemoryService interface
type MemoryService struct {
repo interfaces.MemoryRepository
modelService interfaces.ModelService
}
// NewMemoryService creates a new memory service
func NewMemoryService(repo interfaces.MemoryRepository, modelService interfaces.ModelService) interfaces.MemoryService {
return &MemoryService{
repo: repo,
modelService: modelService,
}
}
const extractGraphPrompt = `
You are an AI assistant that extracts knowledge graphs from conversations.
Given the following conversation, extract entities and relationships.
Output the result in JSON format with the following structure:
{
"summary": "A brief summary of the conversation",
"entities": [
{
"title": "Entity Name",
"type": "Entity Type (e.g., Person, Location, Concept)",
"description": "Description of the entity"
}
],
"relationships": [
{
"source": "Source Entity Name",
"target": "Target Entity Name",
"description": "Description of the relationship",
"weight": 1.0
}
]
}
Conversation:
%s
`
const extractKeywordsPrompt = `
You are an AI assistant that extracts search keywords from a user query.
Given the following query, extract relevant keywords for searching a knowledge graph.
Output the result in JSON format:
{
"keywords": ["keyword1", "keyword2"]
}
Query:
%s
`
type extractionResult struct {
Summary string `json:"summary" jsonschema:"a brief summary of the conversation"`
Entities []*types.Entity `json:"entities"`
Relationships []*types.Relationship `json:"relationships"`
}
type keywordsResult struct {
Keywords []string `json:"keywords" jsonschema:"relevant keywords for searching a knowledge graph"`
}
func (s *MemoryService) getChatModel(ctx context.Context) (chat.Chat, error) {
// Find the first available KnowledgeQA model
models, err := s.modelService.ListModels(ctx)
if err != nil {
return nil, fmt.Errorf("failed to list models: %v", err)
}
var modelID string
for _, model := range models {
if model.Type == types.ModelTypeKnowledgeQA {
modelID = model.ID
break
}
}
if modelID == "" {
return nil, fmt.Errorf("no KnowledgeQA model found")
}
return s.modelService.GetChatModel(ctx, modelID)
}
// AddEpisode adds a new episode to the memory graph
func (s *MemoryService) AddEpisode(ctx context.Context, userID string, sessionID string, messages []types.Message) error {
if !s.repo.IsAvailable(ctx) {
return fmt.Errorf("memory repository is not available")
}
chatModel, err := s.getChatModel(ctx)
if err != nil {
return err
}
// 1. Construct conversation string
var conversation string
for _, msg := range messages {
conversation += fmt.Sprintf("%s: %s\n", msg.Role, msg.Content)
}
// 2. Call LLM to extract graph
prompt := fmt.Sprintf(extractGraphPrompt, conversation)
resp, err := chatModel.Chat(ctx, []chat.Message{{Role: "user", Content: prompt}}, &chat.ChatOptions{
Format: utils.GenerateSchema[extractionResult](),
})
if err != nil {
return fmt.Errorf("failed to call LLM: %v", err)
}
var result extractionResult
if err := json.Unmarshal([]byte(resp.Content), &result); err != nil {
return fmt.Errorf("failed to parse LLM response: %v", err)
}
// 3. Create Episode object
episode := &types.Episode{
ID: uuid.New().String(),
UserID: userID,
SessionID: sessionID,
Summary: result.Summary,
CreatedAt: time.Now(),
}
// 4. Save to repository
if err := s.repo.SaveEpisode(ctx, episode, result.Entities, result.Relationships); err != nil {
return fmt.Errorf("failed to save episode: %v", err)
}
return nil
}
// RetrieveMemory retrieves relevant memory context based on the current query and user
func (s *MemoryService) RetrieveMemory(ctx context.Context, userID string, query string) (*types.MemoryContext, error) {
if !s.repo.IsAvailable(ctx) {
return nil, fmt.Errorf("memory repository is not available")
}
chatModel, err := s.getChatModel(ctx)
if err != nil {
return nil, err
}
// 1. Extract keywords
prompt := fmt.Sprintf(extractKeywordsPrompt, query)
resp, err := chatModel.Chat(ctx, []chat.Message{{Role: "user", Content: prompt}}, &chat.ChatOptions{
Format: utils.GenerateSchema[keywordsResult](),
})
if err != nil {
return nil, fmt.Errorf("failed to call LLM: %v", err)
}
var result keywordsResult
if err := json.Unmarshal([]byte(resp.Content), &result); err != nil {
return nil, fmt.Errorf("failed to parse LLM response: %v", err)
}
// 2. Retrieve related episodes
episodes, err := s.repo.FindRelatedEpisodes(ctx, userID, result.Keywords, 5)
if err != nil {
return nil, fmt.Errorf("failed to find related episodes: %v", err)
}
// 3. Construct MemoryContext
memoryContext := &types.MemoryContext{
RelatedEpisodes: make([]types.Episode, len(episodes)),
}
for i, ep := range episodes {
memoryContext.RelatedEpisodes[i] = *ep
}
return memoryContext, nil
}
-3
View File
@@ -45,7 +45,6 @@ type sessionService struct {
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
kbShareService interfaces.KBShareService // Service for KB sharing operations
memoryService interfaces.MemoryService // Service for memory operations
suggestionRepo interfaces.MessageSuggestionRepository
}
@@ -63,7 +62,6 @@ func NewSessionService(cfg *config.Config,
webSearchStateRepo interfaces.WebSearchStateService,
webSearchProviderRepo interfaces.WebSearchProviderRepository,
kbShareService interfaces.KBShareService,
memoryService interfaces.MemoryService,
suggestionRepo interfaces.MessageSuggestionRepository,
) interfaces.SessionService {
return &sessionService{
@@ -80,7 +78,6 @@ func NewSessionService(cfg *config.Config,
webSearchStateRepo: webSearchStateRepo,
webSearchProviderRepo: webSearchProviderRepo,
kbShareService: kbShareService,
memoryService: memoryService,
suggestionRepo: suggestionRepo,
}
}
@@ -27,11 +27,10 @@ func (s *sessionService) KnowledgeQA(
) error {
logger.Infof(
ctx,
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v, enableMemory: %v",
"Knowledge base question answering parameters, session ID: %s, query: %s, webSearchEnabled: %v",
req.Session.ID,
req.Query,
req.WebSearchEnabled,
req.EnableMemory,
)
// Span the request setup (KB / model resolution, search target building,
@@ -103,15 +102,11 @@ func (s *sessionService) KnowledgeQA(
len(searchTargets),
)
// Scope memory and pipeline attribution to the same owner as the session.
userID := types.SessionOwnerIDFromContext(ctx)
chatManage := &types.ChatManage{
PipelineRequest: types.PipelineRequest{
Query: req.Query,
SessionID: req.Session.ID,
UserID: userID,
EnableMemory: req.EnableMemory,
UserID: types.SessionOwnerIDFromContext(ctx),
MaxRounds: s.cfg.Conversation.MaxRounds,
KnowledgeBaseIDs: knowledgeBaseIDs,
KnowledgeIDs: knowledgeIDs,
@@ -184,9 +179,7 @@ func (s *sessionService) KnowledgeQA(
pipeline = types.NewPipelineBuilder().
AddIf(hasHistory, types.LOAD_HISTORY).
AddIf(chatManage.EnableMemory, types.MEMORY_RETRIEVAL).
Add(types.CHAT_COMPLETION_STREAM).
AddIf(chatManage.EnableMemory, types.MEMORY_STORAGE).
Build()
} else {
// RAG — dynamically assemble based on feature flags.
+1 -5
View File
@@ -585,7 +585,7 @@ func (s *userService) RevokeSystemAdmin(ctx context.Context, userID, actorID str
// UpdateUserPreferences applies a partial update over the user's
// preferences blob. PATCH semantics: only keys present in `patch`
// (non-nil pointer fields) replace the existing value; everything else
// is preserved. This lets the front-end PUT only the toggle that
// is preserved. This lets the front-end PUT only the preference that
// changed without having to read-modify-write the whole struct, and
// also makes the endpoint forward-compatible — older clients that
// don't know about newer keys won't accidentally erase them.
@@ -600,10 +600,6 @@ func (s *userService) UpdateUserPreferences(
}
merged := user.Preferences
if patch.EnableMemory != nil {
v := *patch.EnableMemory
merged.EnableMemory = &v
}
if patch.LastActiveTenantID != nil {
// *0 = "forget my preference, fall back to home on next login";
// any positive value = set/replace. We do not validate membership
-5
View File
@@ -35,7 +35,6 @@ import (
"github.com/Tencent/WeKnora/internal/agent/approval"
"github.com/Tencent/WeKnora/internal/application/repository"
memoryRepo "github.com/Tencent/WeKnora/internal/application/repository/memory/neo4j"
dorisRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/doris"
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
@@ -50,7 +49,6 @@ import (
"github.com/Tencent/WeKnora/internal/application/service"
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
"github.com/Tencent/WeKnora/internal/application/service/file"
memoryService "github.com/Tencent/WeKnora/internal/application/service/memory"
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/common"
"github.com/Tencent/WeKnora/internal/config"
@@ -157,7 +155,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(repository.NewAuthTokenRepository))
must(container.Provide(repository.NewSystemSettingRepository))
must(container.Provide(neo4jRepo.NewNeo4jRepository))
must(container.Provide(memoryRepo.NewMemoryRepository))
must(container.Provide(repository.NewMCPServiceRepository))
must(container.Provide(repository.NewMCPToolApprovalRepository))
must(container.Provide(repository.NewMCPOAuthRepository))
@@ -217,7 +214,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(service.NewMCPToolApprovalService))
must(container.Provide(service.NewCustomAgentService))
must(container.Provide(service.NewUserResourceFavoriteService))
must(container.Provide(memoryService.NewMemoryService))
must(container.Provide(service.NewWikiPageService))
must(container.Provide(service.NewWikiLogEntryService))
must(container.Provide(service.NewWikiIngestService, dig.Name("wikiIngest")))
@@ -337,7 +333,6 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Invoke(chatpipeline.NewPluginSearchEntity))
must(container.Invoke(chatpipeline.NewPluginSearchParallel))
must(container.Invoke(chatpipeline.NewPluginWikiBoost))
must(container.Invoke(chatpipeline.NewMemoryPlugin))
logger.Debugf(ctx, "[Container] Chat pipeline plugins registered")
// HTTP handlers layer
-2
View File
@@ -583,7 +583,6 @@ func (h *AuthHandler) GetCurrentUser(c *gin.Context) {
// (preserve existing value) from "explicit false". See
// types.UserPreferences for the persistence-layer counterpart.
type updateMyPreferencesRequest struct {
EnableMemory *bool `json:"enable_memory"`
// LastActiveTenantID lets the SPA persist "after a fresh login,
// drop me back into this workspace" across devices. Send a positive
// workspace id to set / replace, or 0 to clear. Membership is validated
@@ -623,7 +622,6 @@ func (h *AuthHandler) UpdateMyPreferences(c *gin.Context) {
}
patch := types.UserPreferences{
EnableMemory: req.EnableMemory,
LastActiveTenantID: req.LastActiveTenantID,
}
prefs, err := h.userService.UpdateUserPreferences(ctx, user.ID, patch)
+1 -10
View File
@@ -71,7 +71,6 @@ type embedChannelRequest struct {
ShowSuggestedQuestions *bool `json:"show_suggested_questions"`
WidgetPosition string `json:"widget_position"`
AllowWebSearch *bool `json:"allow_web_search"`
AllowMemory *bool `json:"allow_memory"`
AllowFileUpload *bool `json:"allow_file_upload"`
DefaultLocale *string `json:"default_locale"`
WebhookURL *string `json:"webhook_url"`
@@ -152,10 +151,6 @@ func (h *EmbedChannelHandler) CreateEmbedChannel(c *gin.Context) {
if req.AllowWebSearch != nil {
allowWebSearch = *req.AllowWebSearch
}
allowMemory := false
if req.AllowMemory != nil {
allowMemory = *req.AllowMemory
}
allowFileUpload := false
if req.AllowFileUpload != nil {
allowFileUpload = *req.AllowFileUpload
@@ -173,7 +168,6 @@ func (h *EmbedChannelHandler) CreateEmbedChannel(c *gin.Context) {
ShowSuggestedQuestions: showSuggested,
WidgetPosition: req.WidgetPosition,
AllowWebSearch: allowWebSearch,
AllowMemory: allowMemory,
AllowFileUpload: allowFileUpload,
DefaultLocale: types.NormalizeEmbedDefaultLocale(stringOrEmpty(req.DefaultLocale)),
})
@@ -255,7 +249,7 @@ func (h *EmbedChannelHandler) UpdateEmbedChannel(c *gin.Context) {
if req.AgentID != nil {
update.AgentID = strings.TrimSpace(*req.AgentID)
}
ch, err := h.embedSvc.Update(c.Request.Context(), tenantID, channelID, update, req.Enabled, req.ShowSuggestedQuestions, req.AllowWebSearch, req.AllowMemory, req.AllowFileUpload, req.DefaultLocale, req.WebhookURL, req.WebhookSecret)
ch, err := h.embedSvc.Update(c.Request.Context(), tenantID, channelID, update, req.Enabled, req.ShowSuggestedQuestions, req.AllowWebSearch, req.AllowFileUpload, req.DefaultLocale, req.WebhookURL, req.WebhookSecret)
if err != nil {
writeEmbedMgmtError(c, err)
return
@@ -710,8 +704,6 @@ func patchEmbedChatPayload(body io.Reader, ch *types.EmbedChannel, agentMode boo
}
// Channel allow_web_search only exposes the visitor toggle; the client must opt in.
payload["web_search_enabled"] = ch.AllowWebSearch && clientWebSearch
// Embed memory UI is disabled for now; always off regardless of channel flag.
payload["enable_memory"] = false
if !ch.AllowFileUpload {
delete(payload, "images")
delete(payload, "attachment_uploads")
@@ -796,7 +788,6 @@ func embedChannelResponse(ch *types.EmbedChannel, publishToken string) gin.H {
"show_suggested_questions": ch.ShowSuggestedQuestions,
"widget_position": ch.WidgetPosition,
"allow_web_search": ch.AllowWebSearch,
"allow_memory": ch.AllowMemory,
"allow_file_upload": ch.AllowFileUpload,
"default_locale": ch.DefaultLocale,
"webhook_url": ch.WebhookURL,
@@ -28,7 +28,7 @@ func (f *exchangeEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*type
func (f *exchangeEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
func (f *exchangeEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *exchangeEmbedSvc) GetOwnedChannel(context.Context, uint64, string) (*types.EmbedChannel, error) {
+2 -5
View File
@@ -32,7 +32,7 @@ func (f *flowEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types.Em
func (f *flowEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (f *flowEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
func (f *flowEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
return nil, nil
}
func (f *flowEmbedSvc) GetOwnedChannel(_ context.Context, tenantID uint64, id string) (*types.EmbedChannel, error) {
@@ -214,7 +214,7 @@ func TestPatchEmbedChatPayloadInjectsAgentID(t *testing.T) {
func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) {
ch := &types.EmbedChannel{AgentID: "agent-1", AllowWebSearch: true}
body := `{"query":"hello","web_search_enabled":false,"enable_memory":true}`
body := `{"query":"hello","web_search_enabled":false}`
patched, err := patchEmbedChatPayload(strings.NewReader(body), ch, false)
if err != nil {
@@ -227,9 +227,6 @@ func TestPatchEmbedChatPayloadWebSearchRequiresClientOptIn(t *testing.T) {
if payload["web_search_enabled"] != false {
t.Fatalf("web_search_enabled = %v, want false when visitor did not opt in", payload["web_search_enabled"])
}
if payload["enable_memory"] != false {
t.Fatalf("enable_memory = %v, want false (embed memory is disabled)", payload["enable_memory"])
}
bodyOn := `{"query":"hello","web_search_enabled":true}`
patchedOn, err := patchEmbedChatPayload(strings.NewReader(bodyOn), ch, false)
+1 -1
View File
@@ -78,7 +78,7 @@ func (s *sessionEmbedSvc) ListByAgent(context.Context, uint64, string) ([]*types
func (s *sessionEmbedSvc) ListByTenant(context.Context, uint64) ([]*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
func (s *sessionEmbedSvc) Update(context.Context, uint64, string, *types.EmbedChannel, *bool, *bool, *bool, *bool, *string, *string, *string) (*types.EmbedChannel, error) {
return nil, nil
}
func (s *sessionEmbedSvc) GetOwnedChannel(context.Context, uint64, string) (*types.EmbedChannel, error) {
-3
View File
@@ -29,7 +29,6 @@ type Handler struct {
fileService interfaces.FileService // Service for file storage (image uploads)
storageResolver interfaces.StorageBackendResolver
modelService interfaces.ModelService // Service for model management (VLM access)
userService interfaces.UserService // Service for resolving per-user preferences (e.g. enable_memory default)
attachmentProcessor *AttachmentProcessor // Processor for file attachments
temporaryDocuments interfaces.TemporaryDocumentService
}
@@ -49,7 +48,6 @@ func NewHandler(
fileService interfaces.FileService,
storageResolver interfaces.StorageBackendResolver,
modelService interfaces.ModelService,
userService interfaces.UserService,
documentReader interfaces.DocumentReader,
imageResolver *docparser.ImageResolver,
temporaryDocuments interfaces.TemporaryDocumentService,
@@ -68,7 +66,6 @@ func NewHandler(
fileService: fileService,
storageResolver: storageResolver,
modelService: modelService,
userService: userService,
temporaryDocuments: temporaryDocuments,
attachmentProcessor: NewAttachmentProcessor(
fileService,
-40
View File
@@ -41,7 +41,6 @@ type qaRequestContext struct {
skillNames []string
summaryModelID string
webSearchEnabled bool
enableMemory bool // Whether memory feature is enabled
mentionedItems types.MentionedItems
effectiveTenantID uint64 // when using shared agent, tenant ID for model/KB/MCP resolution; 0 = use context tenant
images []ImageAttachment // Uploaded images with analysis text
@@ -77,7 +76,6 @@ func (rc *qaRequestContext) buildQARequest() *types.QARequest {
ImageDescription: imageDescription,
UserMessageID: rc.userMessageID,
WebSearchEnabled: rc.webSearchEnabled,
EnableMemory: rc.enableMemory,
Attachments: rc.attachments,
}
}
@@ -286,17 +284,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
attachmentIDs = normalizedIDs
}
// Resolve enable_memory:
// 1. Explicit value in request → honour it. Used by embedded mode
// (force false) and by older clients still sending the literal bool.
// 2. Not set → fall back to the calling user's stored preference.
// The toggle is persisted server-side per user (see PUT
// /auth/me/preferences); this is the canonical path for the
// normal logged-in web UI now that it no longer sends the field.
// 3. No user / no preference → false. API-key-only callers never
// had memory enabled in practice, keep that behaviour.
enableMemory := h.resolveEnableMemory(ctx, request.EnableMemory)
mentionScopes := tagScopesFromMentionedItems(request.MentionedItems)
requestTagIDs := dedupRequestStrings(request.TagIDs)
if err := validateUnscopedTagIDs(orphanTagIDsForScope(requestTagIDs, mentionScopes), secutils.SanitizeForLogArray(kbIDs)); err != nil {
@@ -349,7 +336,6 @@ func (h *Handler) parseQARequest(c *gin.Context, logPrefix string) (*qaRequestCo
skillNames: secutils.SanitizeForLogArray(skillNames),
summaryModelID: secutils.SanitizeForLog(request.SummaryModelID),
webSearchEnabled: request.WebSearchEnabled,
enableMemory: enableMemory,
mentionedItems: convertMentionedItems(request.MentionedItems),
effectiveTenantID: effectiveTenantID,
images: request.Images,
@@ -456,32 +442,6 @@ func cloneTagScopes(scopes []types.TagScope) []types.TagScope {
return cloned
}
// resolveEnableMemory decides whether the memory pipeline runs for this
// request. See the call-site comment in parseQARequest for the resolution
// order. Lookup errors are logged but never propagate — a failure to read
// the user's preference shouldn't break the chat request itself, we just
// fall back to false (the safe default).
func (h *Handler) resolveEnableMemory(ctx context.Context, override *bool) bool {
if override != nil {
return *override
}
if h.userService == nil {
return false
}
user, err := h.userService.GetCurrentUser(ctx)
if err != nil {
// API-key-only callers or revoked sessions land here; the chat
// request itself stays authorised via the middleware that already
// ran, we just have nobody to look preferences up for.
logger.Debugf(ctx, "enable_memory: no user in context, defaulting to false: %v", err)
return false
}
if user.Preferences.EnableMemory != nil {
return *user.Preferences.EnableMemory
}
return false
}
// resolveAgent resolves the custom agent by ID, trying shared agent first, then own agent.
// Returns (nil, 0) if agentID is empty or not found.
func (h *Handler) resolveAgent(ctx context.Context, c *gin.Context, agentID string) (*types.CustomAgent, uint64) {
+16 -28
View File
@@ -42,34 +42,22 @@ type ImageAttachment struct {
// CreateKnowledgeQARequest defines the request structure for knowledge QA
type CreateKnowledgeQARequest struct {
Query string `json:"query" binding:"required"` // Query text for knowledge base search
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its workspace from share relation)
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MCPServiceIDs []string `json:"mcp_service_ids"` // Per-request MCP services selected via @mention
SkillNames []string `json:"skill_names"` // Per-request Skills selected via @mention
TagIDs []string `json:"tag_ids"` // @mentioned tag IDs (display/debug; scoped via MentionedItems)
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
// EnableMemory is the per-request override for the memory feature.
// Pointer + omitempty so the request can distinguish three states:
// nil = client did not specify; backend falls back to the calling
// user's persisted preference (user.preferences.enable_memory),
// defaulting to false if that's also unset. This is the path
// used by the normal logged-in chat UI now that the toggle is
// stored server-side per user.
// *true / *false = explicit override. Embedded mode forces *false so a
// user's personal memory setting doesn't leak into a widget
// context; older clients that still send a literal bool also
// land here (back-compat).
EnableMemory *bool `json:"enable_memory,omitempty"`
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
AttachmentIDs []string `json:"attachment_ids,omitempty"` // Pre-uploaded session-scoped document IDs
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
Query string `json:"query" binding:"required"` // Query text for knowledge base search
KnowledgeBaseIDs []string `json:"knowledge_base_ids"` // Selected knowledge base ID for this request
KnowledgeIds []string `json:"knowledge_ids"` // Selected knowledge ID for this request
AgentEnabled bool `json:"agent_enabled"` // Whether agent mode is enabled for this request
AgentID string `json:"agent_id"` // Selected custom agent ID (backend resolves shared agent and its workspace from share relation)
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search is enabled for this request
SummaryModelID string `json:"summary_model_id"` // Optional summary model ID for this request (overrides session default)
MCPServiceIDs []string `json:"mcp_service_ids"` // Per-request MCP services selected via @mention
SkillNames []string `json:"skill_names"` // Per-request Skills selected via @mention
TagIDs []string `json:"tag_ids"` // @mentioned tag IDs (display/debug; scoped via MentionedItems)
MentionedItems []MentionedItemRequest `json:"mentioned_items"` // @mentioned knowledge bases and files
DisableTitle bool `json:"disable_title"` // Whether to disable auto title generation
Images []ImageAttachment `json:"images"` // Attached images for multimodal chat
AttachmentUploads []AttachmentUpload `json:"attachment_uploads,omitempty"` // Attached files (documents, audio, etc.)
AttachmentIDs []string `json:"attachment_ids,omitempty"` // Pre-uploaded session-scoped document IDs
Channel string `json:"channel"` // Source channel: "web", "api", "im", etc.
SuggestionAttribution *types.SuggestionAttribution `json:"suggestion_attribution,omitempty"`
}
+1 -1
View File
@@ -39,7 +39,7 @@ func (f *fakeEmbedChannelService) ListByTenant(
func (f *fakeEmbedChannelService) Update(
ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel,
enabled *bool, showSuggested *bool, allowWebSearch *bool, allowMemory *bool, allowFileUpload *bool,
enabled *bool, showSuggested *bool, allowWebSearch *bool, allowFileUpload *bool,
defaultLocale *string, webhookURL *string, webhookSecret *string,
) (*types.EmbedChannel, error) {
return nil, nil
+4 -10
View File
@@ -4,11 +4,10 @@ import "maps"
// PipelineRequest holds immutable configuration set once at the request entry point.
type PipelineRequest struct {
SessionID string `json:"session_id"`
UserID string `json:"user_id"`
Query string `json:"query,omitempty"`
EnableMemory bool `json:"enable_memory"`
MaxRounds int `json:"max_rounds"`
SessionID string `json:"session_id"`
UserID string `json:"user_id"`
Query string `json:"query,omitempty"`
MaxRounds int `json:"max_rounds"`
// Knowledge base retrieval parameters
KnowledgeBaseIDs []string `json:"knowledge_base_ids"`
@@ -204,7 +203,6 @@ func (c *ChatManage) Clone() *ChatManage {
Query: c.Query,
SessionID: c.SessionID,
UserID: c.UserID,
EnableMemory: c.EnableMemory,
MaxRounds: c.MaxRounds,
KnowledgeBaseIDs: knowledgeBaseIDs,
KnowledgeIDs: knowledgeIDs,
@@ -275,8 +273,6 @@ const (
CHAT_COMPLETION EventType = "chat_completion"
CHAT_COMPLETION_STREAM EventType = "chat_completion_stream"
FILTER_TOP_K EventType = "filter_top_k"
MEMORY_RETRIEVAL EventType = "memory_retrieval"
MEMORY_STORAGE EventType = "memory_storage"
)
// PipelineBuilder dynamically assembles a pipeline as an ordered list of EventTypes.
@@ -321,9 +317,7 @@ var Pipeline = map[string][]EventType{
},
"chat_history_stream": {
LOAD_HISTORY,
MEMORY_RETRIEVAL,
CHAT_COMPLETION_STREAM,
MEMORY_STORAGE,
},
"rag": {
CHUNK_SEARCH,
-2
View File
@@ -27,7 +27,6 @@ type EmbedChannel struct {
ShowSuggestedQuestions bool `json:"show_suggested_questions" gorm:"not null;default:true"`
WidgetPosition string `json:"widget_position" gorm:"type:varchar(32);not null;default:'bottom-right'"`
AllowWebSearch bool `json:"allow_web_search" gorm:"not null;default:false"`
AllowMemory bool `json:"allow_memory" gorm:"not null;default:false"`
AllowFileUpload bool `json:"allow_file_upload" gorm:"not null;default:false"`
DefaultLocale string `json:"default_locale" gorm:"type:varchar(16);not null;default:''"`
WebhookURL string `json:"webhook_url" gorm:"type:varchar(512);not null;default:''"`
@@ -119,7 +118,6 @@ type EmbedChannelPublicConfig struct {
AllowedOrigins []string `json:"allowed_origins,omitempty"`
WidgetPosition string `json:"widget_position,omitempty"`
AllowWebSearch bool `json:"allow_web_search"`
AllowMemory bool `json:"allow_memory"`
AllowFileUpload bool `json:"allow_file_upload"`
// AgentWebSearchEnabled reflects whether the bound agent has web search configured.
AgentWebSearchEnabled bool `json:"agent_web_search_enabled"`
+1 -1
View File
@@ -22,7 +22,7 @@ type EmbedChannelService interface {
Create(ctx context.Context, tenantID uint64, agentID string, req *types.EmbedChannel) (*types.EmbedChannel, string, error)
ListByAgent(ctx context.Context, tenantID uint64, agentID string) ([]*types.EmbedChannel, error)
ListByTenant(ctx context.Context, tenantID uint64) ([]*types.EmbedChannel, error)
Update(ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel, enabled *bool, showSuggested *bool, allowWebSearch *bool, allowMemory *bool, allowFileUpload *bool, defaultLocale *string, webhookURL *string, webhookSecret *string) (*types.EmbedChannel, error)
Update(ctx context.Context, tenantID uint64, id string, req *types.EmbedChannel, enabled *bool, showSuggested *bool, allowWebSearch *bool, allowFileUpload *bool, defaultLocale *string, webhookURL *string, webhookSecret *string) (*types.EmbedChannel, error)
Delete(ctx context.Context, tenantID uint64, id string) error
RotateToken(ctx context.Context, tenantID uint64, id string) (*types.EmbedChannel, string, error)
LookupForEmbed(ctx context.Context, channelID, token string) (*types.EmbedChannel, error)
-28
View File
@@ -1,28 +0,0 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// MemoryService defines the interface for the memory system
type MemoryService interface {
// AddEpisode processes a conversation session and adds it as an episode to the memory graph
AddEpisode(ctx context.Context, userID string, sessionID string, messages []types.Message) error
// RetrieveMemory retrieves relevant memory context based on the current query and user
RetrieveMemory(ctx context.Context, userID string, query string) (*types.MemoryContext, error)
}
// MemoryRepository defines the interface for storing and retrieving memory data
type MemoryRepository interface {
// SaveEpisode saves an episode and its associated entities and relationships to the graph
SaveEpisode(ctx context.Context, episode *types.Episode, entities []*types.Entity, relations []*types.Relationship) error
// FindRelatedEpisodes finds episodes related to the given keywords for a specific user
FindRelatedEpisodes(ctx context.Context, userID string, keywords []string, limit int) ([]*types.Episode, error)
// IsAvailable checks if the memory repository is available
IsAvailable(ctx context.Context) bool
}
-19
View File
@@ -1,19 +0,0 @@
package types
import "time"
// Episode represents a conversation episode or a distinct interaction event
type Episode struct {
ID string `json:"id"`
UserID string `json:"user_id"`
SessionID string `json:"session_id"`
Summary string `json:"summary"`
CreatedAt time.Time `json:"created_at"`
}
// MemoryContext represents the retrieved memory context for a conversation
type MemoryContext struct {
RelatedEpisodes []Episode `json:"related_episodes"`
RelatedEntities []Entity `json:"related_entities"`
RelatedRelations []Relationship `json:"related_relations"`
}
-1
View File
@@ -18,7 +18,6 @@ type QARequest struct {
ImageDescription string // VLM-generated image description (fallback for non-vision models)
UserMessageID string // Created user message ID
WebSearchEnabled bool // Whether web search is enabled for this request
EnableMemory bool // Whether memory feature is enabled
QuotedContext string // Quoted message content from IM quote-reply (appended at LLM prompt stage, not used for retrieval)
Attachments MessageAttachments // File attachments (processed and ready for prompt injection)
}
+2 -7
View File
@@ -9,7 +9,7 @@ import (
"gorm.io/gorm"
)
// UserPreferences holds per-user UI/feature preferences persisted server-side
// UserPreferences holds per-user preferences persisted server-side
// so they sync across devices/browsers. Fields are pointers so we can
// distinguish "client didn't send this key" (leave existing value alone)
// from "client explicitly set false" — the partial-update merge in
@@ -22,11 +22,6 @@ import (
//
// No DB DDL is required — preferences is a single jsonb column.
type UserPreferences struct {
// EnableMemory mirrors the "开启记忆功能" switch in General Settings.
// nil = preference never set (treat as feature default = false)
// *false / *true = user explicitly set the toggle.
EnableMemory *bool `json:"enable_memory,omitempty"`
// LastActiveTenantID remembers the last workspace the user actively
// switched into, so a fresh login (new device, cleared browser, new
// refresh token) lands them back in that workspace instead of always
@@ -95,7 +90,7 @@ type User struct {
CanAccessAllTenants bool `json:"can_access_all_tenants" gorm:"default:false"`
// Whether the user is a system administrator (independent of workspace roles)
IsSystemAdmin bool `json:"is_system_admin" gorm:"default:false;index"`
// Per-user UI/feature preferences (memory toggle, future knobs).
// Per-user UI/feature preferences.
// Stored as JSON (jsonb on Postgres, TEXT on SQLite) via the
// driver.Valuer / sql.Scanner methods on UserPreferences.
Preferences UserPreferences `json:"preferences" gorm:"type:jsonb;not null;default:'{}'"`
-10
View File
@@ -456,7 +456,6 @@ class WeKnoraClient:
query: str,
knowledge_base_ids: list = None,
web_search_enabled: bool = False,
enable_memory: bool = False,
) -> Dict:
"""Send a message to the RAG pipeline (knowledge-chat) and return the assembled answer.
@@ -470,8 +469,6 @@ class WeKnoraClient:
body["knowledge_base_ids"] = knowledge_base_ids
if web_search_enabled:
body["web_search_enabled"] = True
if enable_memory:
body["enable_memory"] = True
result = self._consume_sse_stream(url, body)
result["session_id"] = session_id
return result
@@ -483,7 +480,6 @@ class WeKnoraClient:
agent_id: str,
knowledge_base_ids: list = None,
web_search_enabled: bool = False,
enable_memory: bool = False,
) -> Dict:
"""Send a message to the agentic pipeline (agent-chat) and return the assembled answer.
@@ -498,8 +494,6 @@ class WeKnoraClient:
body["knowledge_base_ids"] = knowledge_base_ids
if web_search_enabled:
body["web_search_enabled"] = True
if enable_memory:
body["enable_memory"] = True
result = self._consume_sse_stream(url, body)
result["session_id"] = session_id
return result
@@ -908,7 +902,6 @@ async def handle_list_tools() -> list[types.Tool]:
"description": "Knowledge base names OR UUIDs to search. Strongly recommended for RAG — without them the answer falls back to LLM knowledge only. E.g. ['my-knowledge-base'] or ['a1b2c3d4-...']. Use list_knowledge_bases to find them.",
},
"web_search_enabled": {"type": "boolean", "description": "Enable web search alongside KB retrieval.", "default": False},
"enable_memory": {"type": "boolean", "description": "Enable cross-session memory.", "default": False},
},
"required": ["session_id", "query"],
},
@@ -940,7 +933,6 @@ async def handle_list_tools() -> list[types.Tool]:
"description": "Names or UUIDs of knowledge bases to search. REQUIRED when the agent's kb_selection_mode is 'none' or 'selected' with no built-in KBs. Use list_knowledge_bases to find them.",
},
"web_search_enabled": {"type": "boolean", "description": "Enable web search.", "default": False},
"enable_memory": {"type": "boolean", "description": "Enable cross-session memory.", "default": False},
},
"required": ["session_id", "query", "agent_id"],
},
@@ -1220,7 +1212,6 @@ async def handle_call_tool(
args["query"],
knowledge_base_ids=kb_ids,
web_search_enabled=args.get("web_search_enabled", False),
enable_memory=args.get("enable_memory", False),
)
# get_running_loop() is the correct API inside async functions (get_event_loop() is deprecated)
result = await asyncio.get_running_loop().run_in_executor(None, fn)
@@ -1271,7 +1262,6 @@ async def handle_call_tool(
agent_id,
knowledge_base_ids=kb_ids,
web_search_enabled=args.get("web_search_enabled", False),
enable_memory=args.get("enable_memory", False),
)
result = await asyncio.get_running_loop().run_in_executor(None, fn)
-1
View File
@@ -704,7 +704,6 @@ CREATE TABLE IF NOT EXISTS embed_channels (
show_suggested_questions INTEGER NOT NULL DEFAULT 1,
widget_position VARCHAR(32) NOT NULL DEFAULT 'bottom-right',
allow_web_search INTEGER NOT NULL DEFAULT 0,
allow_memory INTEGER NOT NULL DEFAULT 0,
allow_file_upload INTEGER NOT NULL DEFAULT 0,
default_locale VARCHAR(16) NOT NULL DEFAULT '',
webhook_url VARCHAR(512) NOT NULL DEFAULT '',