Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(artifacts): artifacts library page backed by a message_artifacts table (#3384)
lyingbug6db8fdd60172
diff --git a/frontend/src/api/artifacts.ts b/frontend/src/api/artifacts.tsnew file mode 100644index 000000000..c4e502717--- /dev/null+++ b/frontend/src/api/artifacts.ts@@ -0,0 +1,49 @@+import { get } from '@/utils/request'++/**+ * One file in the artifact library: the latest version of a file a skill+ * generated in one of the caller's sessions. Download it through+ * downloadArtifact(session_id, message_id, index) from '@/api/chat', which+ * re-checks session ownership server side.+ */+export interface ArtifactLibraryItem {+ session_id: string+ session_title: string+ message_id: string+ index: number+ /** `resource://<handle>` when the deployment runs a resource catalog. */+ handle?: string+ file_name: string+ file_type: string+ file_size: number+ source_path: string+ created_at: string+ /** How many times this file was (re)generated in its session. */+ version_count: number+}++export interface ArtifactLibraryParams {+ keyword?: string+ /** Extensions such as ".pdf"; empty means every type. */+ fileTypes?: string[]+ page?: number+ pageSize?: number+}++export interface ArtifactLibraryPage {+ success: boolean+ data: ArtifactLibraryItem[]+ total: number+ page: number+ page_size: number+}++export function listArtifactLibrary(params: ArtifactLibraryParams = {}) {+ const query: Record<string, string | number> = {}+ const keyword = params.keyword?.trim()+ if (keyword) query.keyword = keyword+ if (params.fileTypes?.length) query.file_types = params.fileTypes.join(',')+ if (params.page) query.page = params.page+ if (params.pageSize) query.page_size = params.pageSize+ return get<ArtifactLibraryPage>('/api/v1/artifacts', { params: query })+}diff --git a/frontend/src/assets/img/artifact-green.svg b/frontend/src/assets/img/artifact-green.svgnew file mode 100644index 000000000..c72801270--- /dev/null+++ b/frontend/src/assets/img/artifact-green.svg@@ -0,0 +1,6 @@+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M10 17.75H5.5C4.53 17.75 3.75 16.97 3.75 16V4C3.75 3.03 4.53 2.25 5.5 2.25H11.5L15.25 6V9" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M11.25 2.25V5C11.25 5.55 11.7 6 12.25 6H15.25" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M6.75 9.25H11.25M6.75 12.25H9.25" stroke="#07C05F" stroke-width="1.5" stroke-linecap="round"/>+ <path d="M14.5 10.75L15.3 12.85C15.4 13.15 15.65 13.4 15.95 13.5L18 14.3L15.95 15.1C15.65 15.2 15.4 15.45 15.3 15.75L14.5 17.8L13.7 15.75C13.6 15.45 13.35 15.2 13.05 15.1L11 14.3L13.05 13.5C13.35 13.4 13.6 13.15 13.7 12.85L14.5 10.75Z" fill="#07C05F" stroke="#07C05F" stroke-width="0.6" stroke-linejoin="round"/>+</svg>diff --git a/frontend/src/assets/img/artifact.svg b/frontend/src/assets/img/artifact.svgnew file mode 100644index 000000000..3178793b1--- /dev/null+++ b/frontend/src/assets/img/artifact.svg@@ -0,0 +1,6 @@+<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">+ <path d="M10 17.75H5.5C4.53 17.75 3.75 16.97 3.75 16V4C3.75 3.03 4.53 2.25 5.5 2.25H11.5L15.25 6V9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M11.25 2.25V5C11.25 5.55 11.7 6 12.25 6H15.25" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M6.75 9.25H11.25M6.75 12.25H9.25" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>+ <path d="M14.5 10.75L15.3 12.85C15.4 13.15 15.65 13.4 15.95 13.5L18 14.3L15.95 15.1C15.65 15.2 15.4 15.45 15.3 15.75L14.5 17.8L13.7 15.75C13.6 15.45 13.35 15.2 13.05 15.1L11 14.3L13.05 13.5C13.35 13.4 13.6 13.15 13.7 12.85L14.5 10.75Z" fill="currentColor" stroke="currentColor" stroke-width="0.6" stroke-linejoin="round"/>+</svg>diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vueindex 666bf24a3..38f9166b0 100644--- a/frontend/src/components/menu.vue+++ b/frontend/src/components/menu.vue@@ -85,7 +85,7 @@<div class="menu_item-box"><div class="menu_icon"><img class="icon"- :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)"+ :src="getImgSrc(item.icon == 'zhishiku' ? knowledgeIcon : item.icon == 'agent' ? agentIcon : item.icon == 'artifact' ? artifactIcon : item.icon == 'organization' ? organizationIcon : item.icon == 'logout' ? logoutIcon : item.icon == 'setting' ? settingIcon : prefixIcon)"alt=""></div><template v-if="!uiStore.sidebarCollapsed">@@ -411,6 +411,8 @@ const isMenuItemActive = (itemPath: string): boolean => {currentRoute === 'knowledgeBaseSettings';case 'agents':return currentRoute === 'agentList';+ case 'artifacts':+ return currentRoute === 'artifactLibrary';case 'organizations':return currentRoute === 'organizationList';case 'creatChat':@@ -439,19 +441,14 @@ const getIconActiveState = (itemPath: string) => {};// 分离上下两部分菜单(使用 visibleMenuArr 以便 lite 模式过滤 logout)+const TOP_MENU_PATHS = new Set(['creatChat', 'knowledge-bases', 'artifacts', 'agents', 'organizations']);+const topMenuItems = computed<MenuItem[]>(() => {- return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) =>- item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat'- );+ return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => TOP_MENU_PATHS.has(item.path));});const bottomMenuItems = computed<MenuItem[]>(() => {- return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => {- if (item.path === 'knowledge-bases' || item.path === 'agents' || item.path === 'organizations' || item.path === 'creatChat') {- return false;- }- return true;- });+ return (visibleMenuArr.value as unknown as MenuItem[]).filter((item: MenuItem) => !TOP_MENU_PATHS.has(item.path));});// 当前知识库信息@@ -1085,6 +1082,7 @@ let prefixIcon = ref('prefixIcon.svg');let logoutIcon = ref('logout.svg');let settingIcon = ref('setting.svg');let agentIcon = ref('agent.svg');+let artifactIcon = ref('artifact.svg');let organizationIcon = ref('organization.svg');let pathPrefix = ref(route.name)const getIcon = (path: string) => {@@ -1093,6 +1091,7 @@ const getIcon = (path: string) => {const creatChatActiveState = getIconActiveState('creatChat');const settingsActiveState = getIconActiveState('settings');const agentsActiveState = route.name === 'agentList';+ const artifactsActiveState = route.name === 'artifactLibrary';const organizationsActiveState = route.name === 'organizationList';// 知识库图标:只在知识库页面显示绿色@@ -1101,6 +1100,9 @@ const getIcon = (path: string) => {// 智能体图标:只在智能体页面显示绿色agentIcon.value = agentsActiveState ? 'agent-green.svg' : 'agent.svg';+ // 产物图标:只在产物页面显示绿色+ artifactIcon.value = artifactsActiveState ? 'artifact-green.svg' : 'artifact.svg';+// 组织图标:只在组织页面显示绿色organizationIcon.value = organizationsActiveState ? 'organization-green.svg' : 'organization.svg';diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 61221a9e1..ae9eaec0d 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -116,10 +116,52 @@ export default {"locateWindow": "Show browser","reconnectShort": "Waiting to reconnect",},+ artifactLibrary: {+ title: 'Artifacts',+ subtitle: 'Files your agents generated across all of your conversations',+ typeFilter: 'Filter by type',+ searchPlaceholder: 'Search filenames',+ categories: {+ all: 'All',+ document: 'Documents',+ spreadsheet: 'Spreadsheets',+ presentation: 'Presentations',+ image: 'Images',+ web: 'Web pages',+ data: 'Data'+ },+ groups: {+ today: 'Today',+ yesterday: 'Yesterday',+ last7Days: 'Last 7 days',+ last30Days: 'Last 30 days',+ earlier: 'Earlier'+ },+ total: '{count} files',+ versions: '{count} versions',+ preview: 'Preview',+ download: 'Download',+ downloadFailed: 'Download failed. Please try again later.',+ openSession: 'Open conversation',+ untitledSession: 'Untitled conversation',+ loadMore: 'Load more',+ loadFailed: 'Could not load artifacts',+ retry: 'Retry',+ clearFilters: 'Clear filters',+ empty: {+ title: 'No artifacts yet',+ description: 'Ask an agent to produce a report, spreadsheet or slide deck and the files will show up here'+ },+ noMatches: {+ title: 'No matching files',+ description: 'Try a different keyword or file type'+ }+ },menu: {sessionInProgress: 'Conversation in progress',knowledgeBase: 'Knowledge Base',agents: 'Agents',+ artifacts: 'Artifacts',organizations: 'Shared Spaces',newChat: 'New Chat',settings: 'System Settings',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 6a66044e0..866e9cc63 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -116,10 +116,52 @@ export default {"locateWindow": "ブラウザーを表示","reconnectShort": "再接続を待機中",},+ artifactLibrary: {+ title: '成果物',+ subtitle: 'すべての会話でエージェントが生成したファイルをまとめて表示します',+ typeFilter: '種類で絞り込む',+ searchPlaceholder: 'ファイル名を検索',+ categories: {+ all: 'すべて',+ document: 'ドキュメント',+ spreadsheet: 'スプレッドシート',+ presentation: 'プレゼンテーション',+ image: '画像',+ web: 'Web ページ',+ data: 'データ'+ },+ groups: {+ today: '今日',+ yesterday: '昨日',+ last7Days: '過去 7 日間',+ last30Days: '過去 30 日間',+ earlier: 'それ以前'+ },+ total: '{count} 件のファイル',+ versions: '{count} バージョン',+ preview: 'プレビュー',+ download: 'ダウンロード',+ downloadFailed: 'ダウンロードに失敗しました。しばらくしてから再試行してください',+ openSession: '会話を開く',+ untitledSession: '無題の会話',+ loadMore: 'さらに読み込む',+ loadFailed: '成果物を読み込めませんでした',+ retry: '再試行',+ clearFilters: '絞り込みを解除',+ empty: {+ title: '成果物はまだありません',+ description: '会話でエージェントにレポートや表、スライドを作成させると、ここに表示されます'+ },+ noMatches: {+ title: '一致するファイルがありません',+ description: '別のキーワードや種類をお試しください'+ }+ },menu: {sessionInProgress: '会話中',knowledgeBase: 'ナレッジベース',agents: 'エージェント',+ artifacts: '成果物',organizations: '共有スペース',newChat: '新しいチャット',settings: 'システム設定',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex d873ede23..cc9f917a4 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -7289,10 +7289,52 @@ export default {references: '참조'}},+ artifactLibrary: {+ title: '산출물',+ subtitle: '모든 대화에서 에이전트가 생성한 파일을 한곳에 모아 보여줍니다',+ typeFilter: '유형별 필터',+ searchPlaceholder: '파일 이름 검색',+ categories: {+ all: '전체',+ document: '문서',+ spreadsheet: '스프레드시트',+ presentation: '프레젠테이션',+ image: '이미지',+ web: '웹 페이지',+ data: '데이터'+ },+ groups: {+ today: '오늘',+ yesterday: '어제',+ last7Days: '최근 7일',+ last30Days: '최근 30일',+ earlier: '이전'+ },+ total: '파일 {count}개',+ versions: '버전 {count}개',+ preview: '미리보기',+ download: '다운로드',+ downloadFailed: '다운로드에 실패했습니다. 잠시 후 다시 시도해 주세요',+ openSession: '대화 열기',+ untitledSession: '제목 없는 대화',+ loadMore: '더 불러오기',+ loadFailed: '산출물을 불러오지 못했습니다',+ retry: '다시 시도',+ clearFilters: '필터 지우기',+ empty: {+ title: '아직 산출물이 없습니다',+ description: '대화에서 에이전트에게 보고서, 표, 슬라이드를 만들게 하면 파일이 여기에 표시됩니다'+ },+ noMatches: {+ title: '일치하는 파일이 없습니다',+ description: '다른 키워드나 파일 유형으로 시도해 보세요'+ }+ },menu: {sessionInProgress: '대화 진행 중',knowledgeBase: '지식베이스',agents: '에이전트',+ artifacts: '산출물',organizations: '공유 공간',newChat: '새 대화',settings: '시스템 설정',diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 5e02ff392..654e2bf0b 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -7289,10 +7289,52 @@ export default {references: 'Источники'}},+ artifactLibrary: {+ title: 'Артефакты',+ subtitle: 'Файлы, созданные агентами во всех ваших диалогах',+ typeFilter: 'Фильтр по типу',+ searchPlaceholder: 'Поиск по имени файла',+ categories: {+ all: 'Все',+ document: 'Документы',+ spreadsheet: 'Таблицы',+ presentation: 'Презентации',+ image: 'Изображения',+ web: 'Веб-страницы',+ data: 'Данные'+ },+ groups: {+ today: 'Сегодня',+ yesterday: 'Вчера',+ last7Days: 'Последние 7 дней',+ last30Days: 'Последние 30 дней',+ earlier: 'Ранее'+ },+ total: 'Файлов: {count}',+ versions: 'Версий: {count}',+ preview: 'Предпросмотр',+ download: 'Скачать',+ downloadFailed: 'Не удалось скачать файл. Повторите попытку позже',+ openSession: 'Открыть диалог',+ untitledSession: 'Диалог без названия',+ loadMore: 'Загрузить ещё',+ loadFailed: 'Не удалось загрузить артефакты',+ retry: 'Повторить',+ clearFilters: 'Сбросить фильтры',+ empty: {+ title: 'Артефактов пока нет',+ description: 'Попросите агента подготовить отчёт, таблицу или презентацию — файлы появятся здесь'+ },+ noMatches: {+ title: 'Нет подходящих файлов',+ description: 'Попробуйте другое ключевое слово или тип файла'+ }+ },menu: {sessionInProgress: 'Диалог выполняется',knowledgeBase: 'База знаний',agents: 'Агенты',+ artifacts: 'Артефакты',organizations: 'Общие пространства',newChat: 'Новый диалог',settings: 'Настройки системы',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 27f4a8c3f..5aacce250 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -7291,10 +7291,52 @@ export default {references: '引用'}},+ artifactLibrary: {+ title: '产物',+ subtitle: '智能体在各个会话中生成的文件,都会汇总在这里',+ typeFilter: '按类型筛选',+ searchPlaceholder: '搜索文件名',+ categories: {+ all: '全部',+ document: '文档',+ spreadsheet: '表格',+ presentation: '演示文稿',+ image: '图片',+ web: '网页',+ data: '数据'+ },+ groups: {+ today: '今天',+ yesterday: '昨天',+ last7Days: '最近 7 天',+ last30Days: '最近 30 天',+ earlier: '更早'+ },+ total: '共 {count} 个文件',+ versions: '{count} 个版本',+ preview: '预览',+ download: '下载',+ downloadFailed: '下载失败,请稍后重试',+ openSession: '打开所在会话',+ untitledSession: '未命名会话',+ loadMore: '加载更多',+ loadFailed: '产物加载失败',+ retry: '重试',+ clearFilters: '清除筛选',+ empty: {+ title: '还没有产物',+ description: '在对话中让智能体生成报告、表格或演示文稿,文件会出现在这里'+ },+ noMatches: {+ title: '没有匹配的文件',+ description: '换个关键词或文件类型试试'+ }+ },menu: {sessionInProgress: '会话进行中',knowledgeBase: '知识库',agents: '智能体',+ artifacts: '产物',organizations: '共享空间',newChat: '新对话',settings: '系统设置',diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex 40280f797..6aa1f0f89 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -133,6 +133,12 @@ const router = createRouter({}},},+ {+ path: "artifacts",+ name: "artifactLibrary",+ component: () => import("../views/artifacts/ArtifactLibrary.vue"),+ meta: { requiresInit: true, requiresAuth: true, requiredCapability: 'settings.sandbox' }+ },{path: "agents",name: "agentList",diff --git a/frontend/src/stores/menu.ts b/frontend/src/stores/menu.tsindex 19ac6d9ed..02a481589 100644--- a/frontend/src/stores/menu.ts+++ b/frontend/src/stores/menu.ts@@ -30,6 +30,8 @@ export const useMenuStore = defineStore('menuStore', () => {children: createMenuChildren()},{ title: '', titleKey: 'menu.knowledgeBase', icon: 'zhishiku', path: 'knowledge-bases' },+ // Artifacts only exist where skills run in a sandbox.+ { title: '', titleKey: 'menu.artifacts', icon: 'artifact', path: 'artifacts', requiredCapability: 'settings.sandbox' },{ title: '', titleKey: 'menu.agents', icon: 'agent', path: 'agents', requiredCapability: 'agents' },{ title: '', titleKey: 'menu.organizations', icon: 'organization', path: 'organizations', requiredCapability: 'organizations' },{ title: '', titleKey: 'menu.settings', icon: 'setting', path: 'settings' },diff --git a/frontend/src/utils/artifactLibrary.test.mjs b/frontend/src/utils/artifactLibrary.test.mjsnew file mode 100644index 000000000..fe3a691d6--- /dev/null+++ b/frontend/src/utils/artifactLibrary.test.mjs@@ -0,0 +1,73 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ ARTIFACT_CATEGORIES,+ artifactCategoryExtensions,+ artifactDateGroup,+ groupArtifactsByDate,+ parseArtifactCategory,+} from './artifactLibrary.ts'++test('"all" sends no extension filter; categories send dotted lowercase extensions', () => {+ assert.deepEqual(artifactCategoryExtensions('all'), [])+ for (const category of ARTIFACT_CATEGORIES.filter((c) => c !== 'all')) {+ const exts = artifactCategoryExtensions(category)+ assert.ok(exts.length > 0, category)+ for (const ext of exts) assert.match(ext, /^\.[a-z0-9]+$/, `${category}: ${ext}`)+ }+ assert.ok(artifactCategoryExtensions('presentation').includes('.pptx'))+})++test('categories do not overlap', () => {+ const seen = new Map()+ for (const category of ARTIFACT_CATEGORIES) {+ for (const ext of artifactCategoryExtensions(category)) {+ assert.equal(seen.get(ext), undefined, `${ext} is in both ${seen.get(ext)} and ${category}`)+ seen.set(ext, category)+ }+ }+})++test('extension lists are copies', () => {+ artifactCategoryExtensions('image').push('.exe')+ assert.ok(!artifactCategoryExtensions('image').includes('.exe'))+})++test('parseArtifactCategory falls back to all', () => {+ assert.equal(parseArtifactCategory('image'), 'image')+ assert.equal(parseArtifactCategory('bogus'), 'all')+ assert.equal(parseArtifactCategory(undefined), 'all')+ assert.equal(parseArtifactCategory(['image']), 'all')+})++test('artifactDateGroup buckets by local calendar day', () => {+ const now = new Date(2026, 8, 18, 9, 0, 0)+ assert.equal(artifactDateGroup(new Date(2026, 8, 18, 0, 5).toISOString(), now), 'today')+ assert.equal(artifactDateGroup(new Date(2026, 8, 17, 23, 59).toISOString(), now), 'yesterday')+ assert.equal(artifactDateGroup(new Date(2026, 8, 13, 12, 0).toISOString(), now), 'last7Days')+ assert.equal(artifactDateGroup(new Date(2026, 8, 1, 12, 0).toISOString(), now), 'last30Days')+ assert.equal(artifactDateGroup(new Date(2026, 5, 1, 12, 0).toISOString(), now), 'earlier')+ assert.equal(artifactDateGroup('not a date', now), 'earlier')+})++test('groupArtifactsByDate keeps order and merges consecutive items', () => {+ const now = new Date(2026, 8, 18, 9, 0, 0)+ const at = (d, h) => new Date(2026, 8, d, h).toISOString()+ const sections = groupArtifactsByDate(+ [+ { id: 1, created_at: at(18, 8) },+ { id: 2, created_at: at(18, 1) },+ { id: 3, created_at: at(17, 20) },+ { id: 4, created_at: at(2, 10) },+ ],+ now,+ )+ assert.deepEqual(+ sections.map((s) => [s.group, s.items.map((i) => i.id)]),+ [+ ['today', [1, 2]],+ ['yesterday', [3]],+ ['last30Days', [4]],+ ],+ )+})diff --git a/frontend/src/utils/artifactLibrary.ts b/frontend/src/utils/artifactLibrary.tsnew file mode 100644index 000000000..c13dffb7a--- /dev/null+++ b/frontend/src/utils/artifactLibrary.ts@@ -0,0 +1,72 @@+/**+ * Type filters for the artifact library page. The server filters by an+ * extension allowlist, so each category is just the extensions it covers.+ */+export type ArtifactCategory = 'all' | 'document' | 'spreadsheet' | 'presentation' | 'image' | 'web' | 'data'++export const ARTIFACT_CATEGORIES: ArtifactCategory[] = [+ 'all',+ 'document',+ 'spreadsheet',+ 'presentation',+ 'image',+ 'web',+ 'data',+]++const CATEGORY_EXTENSIONS: Record<Exclude<ArtifactCategory, 'all'>, string[]> = {+ document: ['.pdf', '.doc', '.docx', '.md', '.txt', '.rtf', '.odt'],+ spreadsheet: ['.xlsx', '.xls', '.csv', '.tsv', '.ods'],+ presentation: ['.pptx', '.ppt', '.key', '.odp'],+ image: ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.bmp'],+ web: ['.html', '.htm'],+ data: ['.json', '.xml', '.yaml', '.yml', '.zip'],+}++/** Extensions to send for a category; empty for "all". */+export function artifactCategoryExtensions(category: ArtifactCategory): string[] {+ return category === 'all' ? [] : [...CATEGORY_EXTENSIONS[category]]+}++/** Parses a ?type= query value, falling back to "all". */+export function parseArtifactCategory(raw: unknown): ArtifactCategory {+ return typeof raw === 'string' && (ARTIFACT_CATEGORIES as string[]).includes(raw)+ ? (raw as ArtifactCategory)+ : 'all'+}++export type ArtifactDateGroup = 'today' | 'yesterday' | 'last7Days' | 'last30Days' | 'earlier'++/** Buckets an ISO timestamp relative to `now`, by local calendar day. */+export function artifactDateGroup(raw: string, now: Date = new Date()): ArtifactDateGroup {+ const at = new Date(raw)+ if (Number.isNaN(at.getTime())) return 'earlier'+ const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()+ const days = Math.round((startOfDay(now) - startOfDay(at)) / 86_400_000)+ if (days <= 0) return 'today'+ if (days === 1) return 'yesterday'+ if (days < 7) return 'last7Days'+ if (days < 30) return 'last30Days'+ return 'earlier'+}++/**+ * Groups items into consecutive date sections. Items arrive newest first, so+ * sections come out in order and a page boundary only ever splits the last one.+ */+export function groupArtifactsByDate<T extends { created_at: string }>(+ items: T[],+ now: Date = new Date(),+): { group: ArtifactDateGroup; items: T[] }[] {+ const sections: { group: ArtifactDateGroup; items: T[] }[] = []+ for (const item of items) {+ const group = artifactDateGroup(item.created_at, now)+ const last = sections[sections.length - 1]+ if (last && last.group === group) {+ last.items.push(item)+ } else {+ sections.push({ group, items: [item] })+ }+ }+ return sections+}diff --git a/frontend/src/views/artifacts/ArtifactLibrary.vue b/frontend/src/views/artifacts/ArtifactLibrary.vuenew file mode 100644index 000000000..e97fbdfd3--- /dev/null+++ b/frontend/src/views/artifacts/ArtifactLibrary.vue@@ -0,0 +1,730 @@+<template>+ <div class="artifact-library">+ <div class="header" style="--wails-draggable: drag">+ <div class="header-title" style="--wails-draggable: drag">+ <h2 style="--wails-draggable: drag">{{ $t('artifactLibrary.title') }}</h2>+ <p class="header-subtitle" style="--wails-draggable: drag">{{ $t('artifactLibrary.subtitle') }}</p>+ </div>+ </div>++ <div class="toolbar">+ <div class="category-tabs" role="tablist" :aria-label="$t('artifactLibrary.typeFilter')">+ <button+ v-for="c in ARTIFACT_CATEGORIES"+ :key="c"+ type="button"+ role="tab"+ :aria-selected="category === c"+ @click="setCategory(c)"+ >+ {{ $t(`artifactLibrary.categories.${c}`) }}+ </button>+ </div>+ <t-input+ v-model="keyword"+ class="search-input"+ :placeholder="$t('artifactLibrary.searchPlaceholder')"+ :aria-label="$t('artifactLibrary.searchPlaceholder')"+ clearable+ >+ <template #prefix-icon><t-icon name="search" size="16px" /></template>+ </t-input>+ </div>++ <div ref="scrollRoot" class="library-main">+ <div v-if="loading && !items.length" class="artifact-rows">+ <div v-for="n in 6" :key="'skel-' + n" class="artifact-row is-skeleton">+ <t-skeleton animation="gradient" :row-col="[[{ width: '32px', height: '38px', type: 'rect' },+ { width: '40%', height: '14px' }]]" />+ </div>+ </div>++ <EmptyState+ v-else-if="loadError && !items.length"+ icon="error-circle"+ :title="$t('artifactLibrary.loadFailed')"+ >+ <t-button variant="outline" @click="reload">{{ $t('artifactLibrary.retry') }}</t-button>+ </EmptyState>++ <EmptyState+ v-else-if="!items.length && isFiltered"+ icon="search"+ :title="$t('artifactLibrary.noMatches.title')"+ :description="$t('artifactLibrary.noMatches.description')"+ >+ <t-button variant="outline" @click="clearFilters">{{ $t('artifactLibrary.clearFilters') }}</t-button>+ </EmptyState>++ <EmptyState+ v-else-if="!items.length"+ icon="folder-open"+ :title="$t('artifactLibrary.empty.title')"+ :description="$t('artifactLibrary.empty.description')"+ />++ <template v-else>+ <div class="result-count">{{ $t('artifactLibrary.total', { count: total }) }}</div>+ <section v-for="section in sections" :key="section.group" class="date-section">+ <h3 class="date-heading">{{ $t(`artifactLibrary.groups.${section.group}`) }}</h3>+ <ul class="artifact-rows">+ <li+ v-for="item in section.items"+ :key="`${item.message_id}:${item.index}`"+ class="artifact-row"+ @click="openPreview(item)"+ >+ <button type="button" class="artifact-open" :title="$t('artifactLibrary.preview')">+ <ArtifactFileIcon :file-name="item.file_name" />+ <span class="artifact-body">+ <span class="artifact-name" :title="item.file_name">{{ item.file_name }}</span>+ <span class="artifact-meta">+ <span>{{ formatArtifactSize(item.file_size) }}</span>+ <span class="meta-sep">·</span>+ <span>{{ formatArtifactDateTime(item.created_at) }}</span>+ <template v-if="item.version_count > 1">+ <span class="meta-sep">·</span>+ <span class="version-badge">+ {{ $t('artifactLibrary.versions', { count: item.version_count }) }}+ </span>+ </template>+ </span>+ </span>+ </button>+ <button+ type="button"+ class="session-link"+ :title="$t('artifactLibrary.openSession')"+ @click.stop="openSession(item)"+ >+ <t-icon name="chat" size="14px" />+ <span>{{ item.session_title || $t('artifactLibrary.untitledSession') }}</span>+ </button>+ <t-button+ class="row-action"+ variant="text"+ shape="square"+ size="small"+ :title="$t('artifactLibrary.download')"+ :aria-label="$t('artifactLibrary.download')"+ :loading="isDownloading(item)"+ @click.stop="handleDownload(item)"+ >+ <template #icon><t-icon name="download" size="16px" /></template>+ </t-button>+ </li>+ </ul>+ </section>++ <div ref="sentinel" class="list-footer">+ <t-loading v-if="loading" size="small" />+ <t-button v-else-if="hasMore" variant="text" @click="loadMore">+ {{ $t('artifactLibrary.loadMore') }}+ </t-button>+ </div>+ </template>+ </div>++ <t-drawer+ v-model:visible="previewVisible"+ class="artifact-library-preview"+ placement="right"+ size="min(880px, 92vw)"+ attach="body"+ :footer="false"+ :close-on-overlay-click="true"+ :close-on-esc-keydown="true"+ @closed="previewItem = null"+ >+ <template #header>+ <div v-if="previewItem" class="preview-header">+ <ArtifactFileIcon class="preview-header-icon" :file-name="previewItem.file_name" />+ <div class="preview-header-text">+ <div class="preview-header-title" :title="previewItem.file_name">{{ previewItem.file_name }}</div>+ <button type="button" class="session-link session-link--inline" @click="openSession(previewItem)">+ <t-icon name="chat" size="12px" />+ <span>{{ previewItem.session_title || $t('artifactLibrary.untitledSession') }}</span>+ </button>+ </div>+ <div ref="previewActions" class="preview-actions" />+ <t-button+ class="row-action"+ variant="text"+ shape="square"+ size="small"+ :title="$t('artifactLibrary.download')"+ :aria-label="$t('artifactLibrary.download')"+ :loading="isDownloading(previewItem)"+ @click="handleDownload(previewItem)"+ >+ <template #icon><t-icon name="download" size="16px" /></template>+ </t-button>+ <t-button+ class="row-action"+ variant="text"+ shape="square"+ size="small"+ :title="$t('common.close')"+ :aria-label="$t('common.close')"+ @click="previewVisible = false"+ >+ <template #icon><t-icon name="close" size="16px" /></template>+ </t-button>+ </div>+ </template>+ <div v-if="previewItem" class="preview-body">+ <DocumentPreview+ :key="`${previewItem.message_id}:${previewItem.index}`"+ :toolbar-target="previewActions"+ :session-id="previewItem.session_id"+ :message-id="previewItem.message_id"+ :artifact-index="previewItem.index"+ :file-type="previewFileType"+ :file-name="previewItem.file_name"+ :active="previewVisible"+ fill-height+ />+ </div>+ </t-drawer>+ </div>+</template>++<script setup lang="ts">+import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'+import { useRoute, useRouter } from 'vue-router'+import { useI18n } from 'vue-i18n'+import { MessagePlugin } from 'tdesign-vue-next'+import { downloadArtifact } from '@/api/chat'+import { listArtifactLibrary, type ArtifactLibraryItem } from '@/api/artifacts'+import {+ ARTIFACT_CATEGORIES,+ artifactCategoryExtensions,+ groupArtifactsByDate,+ parseArtifactCategory,+ type ArtifactCategory,+} from '@/utils/artifactLibrary'+import { formatArtifactDateTime, formatArtifactSize } from '@/utils/sessionArtifacts'+import { resolveFilePreviewExt } from '@/utils/filePreview'+import EmptyState from '@/components/EmptyState.vue'+import DocumentPreview from '@/components/document-preview.vue'+import ArtifactFileIcon from '@/views/chat/components/ArtifactFileIcon.vue'++const PAGE_SIZE = 30+const SEARCH_DEBOUNCE_MS = 300++const { t } = useI18n()+const route = useRoute()+const router = useRouter()++const category = ref<ArtifactCategory>(parseArtifactCategory(route.query.type))+const keyword = ref(typeof route.query.q === 'string' ? route.query.q : '')+const items = ref<ArtifactLibraryItem[]>([])+const total = ref(0)+const page = ref(0)+const loading = ref(false)+const loadError = ref(false)+const downloading = reactive<Record<string, boolean>>({})+const previewItem = ref<ArtifactLibraryItem | null>(null)+const previewVisible = ref(false)+const previewActions = ref<HTMLElement | null>(null)+const scrollRoot = ref<HTMLElement | null>(null)+const sentinel = ref<HTMLElement | null>(null)++const sections = computed(() => groupArtifactsByDate(items.value))+const hasMore = computed(() => items.value.length < total.value)+const isFiltered = computed(() => category.value !== 'all' || keyword.value.trim() !== '')+const previewFileType = computed(() => {+ const item = previewItem.value+ return item ? resolveFilePreviewExt(item.file_name, item.file_type) : ''+})++// Every fetch takes a ticket; a response whose ticket is stale (the filters+// changed while it was in flight) is dropped.+let ticket = 0++async function fetchPage(nextPage: number) {+ const mine = ++ticket+ loading.value = true+ loadError.value = false+ try {+ const res = await listArtifactLibrary({+ keyword: keyword.value,+ fileTypes: artifactCategoryExtensions(category.value),+ page: nextPage,+ pageSize: PAGE_SIZE,+ })+ if (mine !== ticket) return+ const rows = Array.isArray(res?.data) ? res.data : []+ items.value = nextPage === 1 ? rows : [...items.value, ...rows]+ total.value = typeof res?.total === 'number' ? res.total : items.value.length+ page.value = nextPage+ } catch (err) {+ if (mine !== ticket) return+ console.error('[ArtifactLibrary] load failed:', err)+ loadError.value = true+ if (nextPage > 1) MessagePlugin.error(t('artifactLibrary.loadFailed'))+ } finally {+ if (mine === ticket) loading.value = false+ }+}++function reload() {+ items.value = []+ total.value = 0+ page.value = 0+ void fetchPage(1)+}++function loadMore() {+ if (loading.value || !hasMore.value) return+ void fetchPage(page.value + 1)+}++function syncQuery() {+ const query = { ...route.query }+ if (category.value === 'all') delete query.type+ else query.type = category.value+ const q = keyword.value.trim()+ if (q) query.q = q+ else delete query.q+ void router.replace({ query })+}++function setCategory(next: ArtifactCategory) {+ if (category.value === next) return+ category.value = next+}++function clearFilters() {+ category.value = 'all'+ keyword.value = ''+}++let searchTimer: ReturnType<typeof setTimeout> | null = null+watch(keyword, () => {+ if (searchTimer) clearTimeout(searchTimer)+ searchTimer = setTimeout(() => {+ searchTimer = null+ syncQuery()+ reload()+ }, SEARCH_DEBOUNCE_MS)+})+watch(category, () => {+ syncQuery()+ reload()+})++function openPreview(item: ArtifactLibraryItem) {+ previewItem.value = item+ previewVisible.value = true+}++function openSession(item: ArtifactLibraryItem) {+ previewVisible.value = false+ void router.push(`/platform/chat/${item.session_id}`)+}++function downloadKey(item: ArtifactLibraryItem) {+ return `${item.message_id}:${item.index}`+}++function isDownloading(item: ArtifactLibraryItem) {+ return !!downloading[downloadKey(item)]+}++async function handleDownload(item: ArtifactLibraryItem) {+ const key = downloadKey(item)+ if (downloading[key]) return+ downloading[key] = true+ try {+ const blob = await downloadArtifact(item.session_id, item.message_id, item.index)+ const url = URL.createObjectURL(blob)+ const a = document.createElement('a')+ a.href = url+ a.download = item.file_name || 'artifact'+ document.body.appendChild(a)+ a.click()+ document.body.removeChild(a)+ setTimeout(() => URL.revokeObjectURL(url), 1000)+ } catch (err) {+ console.error('[ArtifactLibrary] download failed:', err)+ MessagePlugin.error(t('artifactLibrary.downloadFailed'))+ } finally {+ downloading[key] = false+ }+}++// Load the next page as the footer scrolls into view; the footer button+// covers browsers without IntersectionObserver and failed auto-loads.+let observer: IntersectionObserver | null = null+watch(sentinel, (el, prev) => {+ if (prev) observer?.unobserve(prev)+ if (el) observer?.observe(el)+})++onMounted(() => {+ if (typeof IntersectionObserver !== 'undefined') {+ observer = new IntersectionObserver(+ (entries) => {+ if (entries.some((e) => e.isIntersecting) && !loadError.value) loadMore()+ },+ { root: scrollRoot.value, rootMargin: '200px' },+ )+ if (sentinel.value) observer.observe(sentinel.value)+ }+ void fetchPage(1)+})++onBeforeUnmount(() => {+ observer?.disconnect()+ if (searchTimer) clearTimeout(searchTimer)+ ticket+++})+</script>++<style scoped lang="less">+.artifact-library {+ flex: 1;+ min-width: 0;+ height: 100%;+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ margin: 0 16px 0 0;+ padding: 20px 28px 0;+}++.header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 16px;+ flex-shrink: 0;++ .header-title {+ display: flex;+ flex-direction: column;+ gap: 4px;+ }++ h2 {+ margin: 0;+ color: var(--td-text-color-primary);+ font-family: var(--app-font-family);+ font-size: var(--app-text-4xl);+ font-weight: 600;+ line-height: 32px;+ }+}++.header-subtitle {+ margin: 0;+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-base);+ line-height: 20px;+}++.toolbar {+ flex-shrink: 0;+ display: flex;+ align-items: center;+ justify-content: space-between;+ flex-wrap: wrap;+ gap: var(--app-space-3);+ padding-bottom: var(--app-space-3);+ border-bottom: 1px solid var(--td-component-stroke);+}++.category-tabs {+ display: inline-flex;+ flex-wrap: wrap;+ gap: 2px;+ padding: 3px;+ border-radius: var(--app-radius-md);+ background: var(--td-bg-color-secondarycontainer);++ button {+ padding: 5px 12px;+ border: 0;+ border-radius: var(--app-radius-sm);+ background: transparent;+ color: var(--td-text-color-secondary);+ font: inherit;+ font-size: var(--app-text-md);+ cursor: pointer;+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;++ &:hover {+ color: var(--td-text-color-primary);+ }++ &[aria-selected='true'] {+ background: var(--td-bg-color-container);+ color: var(--td-text-color-primary);+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);+ }++ &:focus-visible {+ outline: 2px solid var(--td-brand-color);+ outline-offset: 2px;+ }+ }+}++.search-input {+ width: 260px;+ max-width: 100%;+}++.library-main {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ overflow-x: hidden;+ display: flex;+ flex-direction: column;+ padding: var(--app-space-3) 0 var(--app-space-6);+}++.result-count {+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ padding: 0 var(--app-space-2) var(--app-space-1);+}++.date-section + .date-section {+ margin-top: var(--app-space-3);+}++.date-heading {+ margin: 0;+ padding: var(--app-space-2) var(--app-space-2) var(--app-space-1);+ color: var(--td-text-color-secondary);+ font-size: var(--app-text-sm);+ font-weight: 500;+}++.artifact-rows {+ margin: 0;+ padding: 0;+ list-style: none;+}++.artifact-row {+ display: flex;+ align-items: center;+ gap: var(--app-space-3);+ padding: 10px var(--app-space-2);+ border-radius: var(--app-radius-md);+ cursor: pointer;+ transition: background var(--app-motion-fast) ease;++ &:hover {+ background: var(--td-bg-color-container-hover);+ }++ &.is-skeleton {+ cursor: default;++ &:hover {+ background: transparent;+ }+ }+}++.artifact-open {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ gap: var(--app-space-3);+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;++ &:focus-visible {+ outline: 2px solid var(--td-text-color-secondary);+ outline-offset: 4px;+ border-radius: var(--app-radius-xs);+ }+}++.artifact-body {+ flex: 1;+ min-width: 0;+}++.artifact-name {+ display: block;+ color: var(--td-text-color-primary);+ font-size: var(--app-text-base);+ font-weight: 500;+ line-height: 1.4;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.artifact-meta {+ margin-top: 2px;+ display: flex;+ align-items: center;+ gap: var(--app-space-1);+ color: var(--td-text-color-placeholder);+ font-size: var(--app-text-sm);+ line-height: 1.3;+ white-space: nowrap;+}++.meta-sep {+ opacity: 0.6;+}++.version-badge {+ color: var(--td-text-color-secondary);+}++.session-link {+ flex: 0 1 240px;+ min-width: 0;+ display: inline-flex;+ align-items: center;+ gap: var(--app-space-1);+ padding: 4px 8px;+ border: 0;+ border-radius: var(--app-radius-sm);+ background: transparent;+ color: var(--td-text-color-secondary);+ font: inherit;+ font-size: var(--app-text-sm);+ cursor: pointer;+ transition: background var(--app-motion-fast) ease, color var(--app-motion-fast) ease;++ span {+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ }++ .t-icon {+ flex-shrink: 0;+ }++ &:hover {+ background: var(--td-bg-color-secondarycontainer);+ color: var(--td-brand-color);+ }++ &:focus-visible {+ outline: 2px solid var(--td-brand-color);+ outline-offset: 2px;+ }++ &--inline {+ flex: none;+ max-width: 100%;+ padding: 0;+ margin-top: 2px;++ &:hover {+ background: transparent;+ }+ }+}++.row-action.t-button {+ flex-shrink: 0;+ width: 30px;+ height: 30px;+ border-radius: var(--app-radius-sm);+ color: var(--td-text-color-secondary);++ &:not(.t-is-disabled):not(.t-is-loading):hover {+ background: color-mix(in srgb, var(--td-text-color-primary) 10%, var(--td-bg-color-container));+ color: var(--td-text-color-primary);+ }++ :deep(.t-button__icon) {+ margin: 0;+ }+}++.list-footer {+ display: flex;+ justify-content: center;+ min-height: 40px;+ padding-top: var(--app-space-3);+}++@media (max-width: 720px) {+ .artifact-library {+ margin: 0;+ padding: var(--app-space-4) var(--app-space-4) 0;+ }++ .search-input {+ width: 100%;+ }++ .session-link:not(.session-link--inline) {+ display: none;+ }+}+</style>++<style lang="less">+.artifact-library-preview {+ .t-drawer__header {+ padding: 10px 16px;+ }++ .t-drawer__body {+ padding: 8px;+ display: flex;+ flex-direction: column;+ }++ .preview-header {+ display: flex;+ align-items: center;+ gap: var(--app-space-2);+ width: 100%;+ min-width: 0;+ }++ .preview-header-icon {+ width: 26px;+ height: 32px;+ }++ .preview-header-text {+ flex: 1;+ min-width: 0;+ }++ .preview-header-title {+ color: var(--td-text-color-primary);+ font-size: var(--app-text-md);+ font-weight: 600;+ line-height: 1.4;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+ }++ .preview-actions {+ flex-shrink: 0;+ }++ .preview-body {+ flex: 1;+ min-height: 0;+ display: flex;+ flex-direction: column;+ }+}+</style>diff --git a/internal/application/repository/message.go b/internal/application/repository/message.goindex c5299b7fe..19ccf13b9 100644--- a/internal/application/repository/message.go+++ b/internal/application/repository/message.go@@ -27,7 +27,13 @@ func NewMessageRepository(db *gorm.DB) interfaces.MessageRepository {func (r *messageRepository) CreateMessage(ctx context.Context, message *types.Message,) (*types.Message, error) {- if err := r.db.WithContext(ctx).Create(message).Error; err != nil {+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ if err := tx.Create(message).Error; err != nil {+ return err+ }+ return insertMessageArtifacts(tx, []*types.Message{message})+ })+ if err != nil {return nil, err}return message, nil@@ -43,6 +49,9 @@ func (r *messageRepository) GetMessage().First(&message).Error; err != nil {return nil, err}+ if err := attachArtifacts(ctx, r.db, &message); err != nil {+ return nil, err+ }return &message, nil}@@ -61,6 +70,9 @@ func (r *messageRepository) GetMessagesBySession(Offset((page - 1) * pageSize).Limit(pageSize).Find(&messages).Error; err != nil {return nil, err}+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {+ return nil, err+ }return messages, nil}@@ -87,6 +99,9 @@ func (r *messageRepository) GetRecentMessagesBySession(}return cmp})+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {+ return nil, err+ }return messages, nil}@@ -110,6 +125,9 @@ func (r *messageRepository) GetMessagesBySessionBeforeTime(}return cmp})+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {+ return nil, err+ }return messages, nil}@@ -127,6 +145,9 @@ func (r *messageRepository) ListMessagesBySessionAfterTime(if err := query.Order("created_at ASC").Limit(limit).Find(&messages).Error; err != nil {return nil, err}+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {+ return nil, err+ }return messages, nil}@@ -137,8 +158,13 @@ func (r *messageRepository) ListMessagesBySessionAfterCursor(ctx context.Contextif !cursor.At.IsZero() || cursor.ID != "" {query = query.Where("created_at > ? OR (created_at = ? AND id > ?)", cursor.At, cursor.At, cursor.ID)}- err := query.Order("created_at ASC, id ASC").Limit(limit).Find(&messages).Error- return messages, err+ if err := query.Order("created_at ASC, id ASC").Limit(limit).Find(&messages).Error; err != nil {+ return nil, err+ }+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {+ return nil, err+ }+ return messages, nil}// ListMessagesBySessionUpTo returns every message of a session that sorts@@ -159,14 +185,23 @@ func (r *messageRepository) ListMessagesBySessionUpTo(Find(&messages).Error; err != nil {return nil, err}+ if err := attachArtifacts(ctx, r.db, messages...); err != nil {+ return nil, err+ }return messages, nil}-// UpdateMessage updates an existing message.+// UpdateMessage updates an existing message. Artifacts are rewritten only+// when message.Artifacts is non-nil (see writeMessageArtifacts).func (r *messageRepository) UpdateMessage(ctx context.Context, message *types.Message) error {- return r.db.WithContext(ctx).Model(&types.Message{}).Where(- "id = ? AND session_id = ?", message.ID, message.SessionID,- ).Updates(message).Error+ return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {+ if err := tx.Model(&types.Message{}).Where(+ "id = ? AND session_id = ?", message.ID, message.SessionID,+ ).Updates(message).Error; err != nil {+ return err+ }+ return writeMessageArtifacts(tx, message)+ })}// DeleteMessage deletes a message@@ -184,6 +219,9 @@ func (r *messageRepository) GetFirstMessageOfUser(ctx context.Context, sessionID).Order("created_at ASC").First(&message).Error; err != nil {return nil, err}+ if err := attachArtifacts(ctx, r.db, &message); err != nil {+ return nil, err+ }return &message, nil}@@ -203,6 +241,9 @@ func (r *messageRepository) GetMessageByRequestID(}return nil, result.Error}+ if err := attachArtifacts(ctx, r.db, &message); err != nil {+ return nil, err+ }return &message, nil}@@ -247,6 +288,9 @@ func (r *messageRepository) SearchMessagesByKeyword(if err := query.Order("messages.created_at DESC").Limit(limit).Find(&results).Error; err != nil {return nil, err}+ if err := attachArtifactsWithSession(ctx, r.db, results); err != nil {+ return nil, err+ }return results, nil}@@ -299,6 +343,9 @@ func (r *messageRepository) GetMessagesByKnowledgeIDs(Find(&results).Error; err != nil {return nil, err}+ if err := attachArtifactsWithSession(ctx, r.db, results); err != nil {+ return nil, err+ }return results, nil}@@ -321,6 +368,9 @@ func (r *messageRepository) GetMessagesByRequestIDs(Find(&results).Error; err != nil {return nil, err}+ if err := attachArtifactsWithSession(ctx, r.db, results); err != nil {+ return nil, err+ }return results, nil}@@ -371,43 +421,6 @@ func (r *messageRepository) UpdateMessageKnowledgeID(Update("knowledge_id", knowledgeID).Error}-// GetSessionArtifacts returns every skill-produced MessageArtifact recorded-// against any assistant message of the session, in creation order.-//-// Projection is scoped to the artifacts JSONB column plus created_at (used-// to order the flattened output). Assistant messages without artifacts (the-// common case) contribute an empty slice and cost nothing extra.-func (r *messageRepository) GetSessionArtifacts(- ctx context.Context, sessionID string,-) (types.MessageArtifacts, error) {- if sessionID == "" {- return nil, nil- }- var rows []struct {- Artifacts types.MessageArtifacts `gorm:"column:artifacts"`- CreatedAt time.Time `gorm:"column:created_at"`- }- if err := r.db.WithContext(ctx).- Model(&types.Message{}).- Select("artifacts", "created_at").- Where("session_id = ? AND deleted_at IS NULL", sessionID).- Order("created_at ASC").- Find(&rows).Error; err != nil {- return nil, err- }- if len(rows) == 0 {- return types.MessageArtifacts{}, nil- }- result := make(types.MessageArtifacts, 0, len(rows))- for _, row := range rows {- if len(row.Artifacts) == 0 {- continue- }- result = append(result, row.Artifacts...)- }- return result, nil-}-// RewriteSandboxCheckpoints retargets copied checkpoints onto the forked// session's live sandbox. CommitSHA / CommittedAt are left untouched: the git// objects are in the snapshot, only the sandbox identity changed.@@ -442,39 +455,6 @@ func (r *messageRepository) RewriteSandboxCheckpoints(return nil}-// RecordRestoredArtifactMtime updates ModTime (and ContentHash) on artifacts-// in this session whose source path matches a same-content sandbox restore.-func (r *messageRepository) RecordRestoredArtifactMtime(- ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,-) error {- if sessionID == "" || sourcePath == "" {- return nil- }- var messages []*types.Message- if err := r.db.WithContext(ctx).- Select("id", "session_id", "artifacts").- Where("session_id = ?", sessionID).- Find(&messages).Error; err != nil {- return err- }- for _, message := range messages {- if message == nil {- continue- }- updated, changed := message.Artifacts.WithRestoredMtime(sourcePath, mod, hash)- if !changed {- continue- }- if err := r.db.WithContext(ctx).- Model(&types.Message{}).- Where("id = ? AND session_id = ?", message.ID, sessionID).- Update("artifacts", updated).Error; err != nil {- return err- }- }- return nil-}-// GetSessionAttachments returns every user-uploaded attachment in creation// order while projecting only the attachments JSON column.func (r *messageRepository) GetSessionAttachments(diff --git a/internal/application/repository/message_artifact.go b/internal/application/repository/message_artifact.gonew file mode 100644index 000000000..ac71c7d9a--- /dev/null+++ b/internal/application/repository/message_artifact.go@@ -0,0 +1,250 @@+package repository++import (+ "context"+ "strings"+ "time"++ "gorm.io/gorm"++ "github.com/Tencent/WeKnora/internal/types"+)++// Artifacts live in message_artifacts, not on the message row. Every loader in+// this package that returns messages goes through attachArtifacts, and every+// writer goes through writeMessageArtifacts, so callers keep working with+// Message.Artifacts as if it were a column.++// artifactLoadBatch bounds the IN list when loading artifacts for many+// messages; SQLite caps bound parameters per statement.+const artifactLoadBatch = 500++// writeMessageArtifacts replaces the stored artifacts of one message. A nil+// list means "not loaded" and leaves the rows untouched; an empty non-nil list+// clears them.+func writeMessageArtifacts(tx *gorm.DB, message *types.Message) error {+ if message == nil || message.Artifacts == nil || message.ID == "" {+ return nil+ }+ if err := tx.Where("message_id = ?", message.ID).+ Delete(&types.MessageArtifactRecord{}).Error; err != nil {+ return err+ }+ rows := types.NewMessageArtifactRecords(message.SessionID, message.ID, message.Artifacts)+ if len(rows) == 0 {+ return nil+ }+ return tx.CreateInBatches(rows, 100).Error+}++// insertMessageArtifacts writes the artifacts of freshly created messages.+// Unlike writeMessageArtifacts it skips the delete, since new messages have+// no rows yet.+func insertMessageArtifacts(tx *gorm.DB, messages []*types.Message) error {+ var rows []types.MessageArtifactRecord+ for _, m := range messages {+ if m == nil || m.ID == "" {+ continue+ }+ rows = append(rows, types.NewMessageArtifactRecords(m.SessionID, m.ID, m.Artifacts)...)+ }+ if len(rows) == 0 {+ return nil+ }+ return tx.CreateInBatches(rows, 100).Error+}++// loadArtifactsByMessage returns each message's artifacts in position order.+// Every requested id is present in the result, with an empty list when the+// message has none.+func loadArtifactsByMessage(+ ctx context.Context, db *gorm.DB, messageIDs []string,+) (map[string]types.MessageArtifacts, error) {+ out := make(map[string]types.MessageArtifacts, len(messageIDs))+ for _, id := range messageIDs {+ out[id] = types.MessageArtifacts{}+ }+ for start := 0; start < len(messageIDs); start += artifactLoadBatch {+ end := min(start+artifactLoadBatch, len(messageIDs))+ var rows []types.MessageArtifactRecord+ if err := db.WithContext(ctx).+ Where("message_id IN ?", messageIDs[start:end]).+ Order("message_id ASC, position ASC").+ Find(&rows).Error; err != nil {+ return nil, err+ }+ for _, row := range rows {+ out[row.MessageID] = append(out[row.MessageID], row.Artifact())+ }+ }+ return out, nil+}++// attachArtifacts fills Message.Artifacts on every message in place.+func attachArtifacts(ctx context.Context, db *gorm.DB, messages ...*types.Message) error {+ ids := make([]string, 0, len(messages))+ for _, m := range messages {+ if m != nil && m.ID != "" {+ ids = append(ids, m.ID)+ }+ }+ if len(ids) == 0 {+ return nil+ }+ byMessage, err := loadArtifactsByMessage(ctx, db, ids)+ if err != nil {+ return err+ }+ for _, m := range messages {+ if m != nil && m.ID != "" {+ m.Artifacts = byMessage[m.ID]+ }+ }+ return nil+}++// attachArtifactsWithSession is attachArtifacts for search-style results.+func attachArtifactsWithSession(ctx context.Context, db *gorm.DB, results []*types.MessageWithSession) error {+ messages := make([]*types.Message, 0, len(results))+ for _, r := range results {+ if r != nil {+ messages = append(messages, &r.Message)+ }+ }+ return attachArtifacts(ctx, db, messages...)+}++// GetSessionArtifacts returns every skill-produced MessageArtifact recorded+// against a live message of the session, in message then position order.+func (r *messageRepository) GetSessionArtifacts(+ ctx context.Context, sessionID string,+) (types.MessageArtifacts, error) {+ if sessionID == "" {+ return nil, nil+ }+ var rows []types.MessageArtifactRecord+ if err := r.db.WithContext(ctx).+ Table("message_artifacts AS ma").+ Select("ma.*").+ Joins("JOIN messages m ON m.id = ma.message_id AND m.deleted_at IS NULL").+ Where("ma.session_id = ?", sessionID).+ Order("m.created_at ASC, m.id ASC, ma.position ASC").+ Find(&rows).Error; err != nil {+ return nil, err+ }+ result := make(types.MessageArtifacts, 0, len(rows))+ for _, row := range rows {+ result = append(result, row.Artifact())+ }+ return result, nil+}++// RecordRestoredArtifactMtime stamps a same-content sandbox restore's mtime+// onto this session's artifacts at sourcePath whose content already hashed to+// hash, mirroring MessageArtifacts.WithRestoredMtime: other versions at the+// path and empty-hash legacy rows are left alone.+func (r *messageRepository) RecordRestoredArtifactMtime(+ ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,+) error {+ if sessionID == "" || sourcePath == "" || hash == "" {+ return nil+ }+ var rows []types.MessageArtifactRecord+ if err := r.db.WithContext(ctx).+ Where("session_id = ? AND source_path = ? AND content_hash = ?", sessionID, sourcePath, hash).+ Find(&rows).Error; err != nil {+ return err+ }+ for _, row := range rows {+ if types.ParseArtifactModTime(row.ModTime).Equal(mod) {+ continue+ }+ if err := r.db.WithContext(ctx).+ Model(&types.MessageArtifactRecord{}).+ Where("id = ?", row.ID).+ Update("mod_time", types.FormatArtifactModTime(mod)).Error; err != nil {+ return err+ }+ }+ return nil+}++// ListArtifactLibrary returns the latest version of every artifact in the+// sessions the caller can see, newest first.+//+// Session visibility mirrors the home sidebar, i.e. the "web" bucket of+// sessionRepository.QueryPaged: same tenant, not deleted, owned by the user or+// a legacy tenant-level row, not a skill-maintenance session, and not an IM,+// embed or API session. IM sessions are created without an owner, so without+// the web predicate every member would see every IM chat's files. Artifacts+// of soft-deleted messages are hidden. Versions are grouped by (session, source path); artifacts without a+// source path stand alone. A later answer that references an earlier file+// stores another row with the same URL, so versions are counted as distinct+// URLs (the max DENSE_RANK over url, since window functions reject DISTINCT).+func (r *messageRepository) ListArtifactLibrary(+ ctx context.Context, q *types.ArtifactLibraryQuery,+) ([]*types.ArtifactLibraryItem, int64, error) {+ var (+ where []string+ args []any+ )+ where = append(where, "s.tenant_id = ?", "s.deleted_at IS NULL")+ args = append(args, q.TenantID)+ if q.UserID != "" {+ where = append(where, "(s.user_id = ? OR s.user_id IS NULL OR s.user_id = '')")+ args = append(args, q.UserID)+ }+ where = append(where, "(s.description IS NULL OR s.description NOT LIKE ?)", webSessionPredicate)+ args = append(args, types.SkillMaintenanceSessionMarker+"%")+ args = append(args, webSessionPredicateArgs()...)+ if kw := strings.TrimSpace(q.Keyword); kw != "" {+ where = append(where, "LOWER(ma.file_name) LIKE LOWER(?) ESCAPE ?")+ args = append(args, "%"+escapeLikeKeyword(kw)+"%", likeEscapeChar)+ }+ if len(q.FileTypes) > 0 {+ where = append(where, "LOWER(ma.file_type) IN ?")+ args = append(args, q.FileTypes)+ }++ grouped := `SELECT ma.session_id, ma.message_id, ma.position, ma.url, ma.file_name,+ ma.file_type, ma.file_size, ma.source_path, ma.created_at, ma.id,+ s.title AS session_title,+ CASE WHEN ma.source_path = '' THEN ma.id ELSE ma.source_path END AS version_key,+ ROW_NUMBER() OVER (+ PARTITION BY ma.session_id, CASE WHEN ma.source_path = '' THEN ma.id ELSE ma.source_path END+ ORDER BY ma.created_at DESC, m.created_at DESC, ma.position DESC+ ) AS version_rank,+ DENSE_RANK() OVER (+ PARTITION BY ma.session_id, CASE WHEN ma.source_path = '' THEN ma.id ELSE ma.source_path END+ ORDER BY ma.url+ ) AS url_rank+ FROM message_artifacts ma+ JOIN messages m ON m.id = ma.message_id AND m.deleted_at IS NULL+ JOIN sessions s ON s.id = ma.session_id+ LEFT JOIN im_channel_sessions ics ON ics.session_id = s.id+ WHERE ` + strings.Join(where, " AND ")+ ranked := `SELECT g.*, MAX(g.url_rank) OVER (PARTITION BY g.session_id, g.version_key) AS version_count+ FROM (` + grouped + `) g`++ var total int64+ if err := r.db.WithContext(ctx).+ Raw("SELECT COUNT(*) FROM ("+ranked+") latest WHERE version_rank = 1", args...).+ Scan(&total).Error; err != nil {+ return nil, 0, err+ }++ page := max(q.Page, 1)+ size := q.PageSize+ if size < 1 {+ size = 20+ }+ items := make([]*types.ArtifactLibraryItem, 0)+ listArgs := append(append([]any{}, args...), size, (page-1)*size)+ if err := r.db.WithContext(ctx).+ Raw("SELECT * FROM ("+ranked+") latest WHERE version_rank = 1 "++ "ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?", listArgs...).+ Scan(&items).Error; err != nil {+ return nil, 0, err+ }+ return items, total, nil+}diff --git a/internal/application/repository/message_artifact_test.go b/internal/application/repository/message_artifact_test.gonew file mode 100644index 000000000..f56ee9f6a--- /dev/null+++ b/internal/application/repository/message_artifact_test.go@@ -0,0 +1,268 @@+package repository++import (+ "context"+ "testing"+ "time"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/require"+ "gorm.io/driver/sqlite"+ "gorm.io/gorm"+)++func newArtifactTestDB(t *testing.T) *gorm.DB {+ t.Helper()+ db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})+ require.NoError(t, err)+ require.NoError(t, db.AutoMigrate(+ &types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}, &testIMChannelSession{},+ ))+ return db+}++func testArtifact(name, sourcePath string, created time.Time) types.MessageArtifact {+ return types.MessageArtifact{+ URL: "local://blobs/" + name,+ FileName: name,+ FileType: ".pptx",+ FileSize: 1024,+ SourcePath: sourcePath,+ // Nanoseconds on purpose: the collector matches files on the exact mtime.+ ModTime: time.Date(2026, 9, 1, 10, 0, 0, 123456789, time.FixedZone("CST", 8*3600)),+ CreatedAt: created,+ }+}++func createSession(t *testing.T, db *gorm.DB, s *types.Session) string {+ t.Helper()+ require.NoError(t, db.Create(s).Error)+ return s.ID+}++func TestMessageArtifactsRoundTripThroughTable(t *testing.T) {+ db := newArtifactTestDB(t)+ repo := NewMessageRepository(db)+ ctx := context.Background()+ created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)++ msg, err := repo.CreateMessage(ctx, &types.Message{+ SessionID: "s1", RequestID: "r1", Role: "assistant",+ Artifacts: types.MessageArtifacts{+ testArtifact("a.pptx", "/w/a.pptx", created),+ testArtifact("b.pptx", "/w/b.pptx", created),+ },+ })+ require.NoError(t, err)++ var stored int64+ require.NoError(t, db.Model(&types.MessageArtifactRecord{}).Where("message_id = ?", msg.ID).Count(&stored).Error)+ require.EqualValues(t, 2, stored, "artifacts are written to message_artifacts")++ got, err := repo.GetMessage(ctx, "s1", msg.ID)+ require.NoError(t, err)+ require.Len(t, got.Artifacts, 2)+ require.Equal(t, "a.pptx", got.Artifacts[0].FileName)+ require.Equal(t, "b.pptx", got.Artifacts[1].FileName)+ require.True(t, got.Artifacts[0].ModTime.Equal(testArtifact("", "", created).ModTime),+ "mtime survives at nanosecond precision")+ require.True(t, got.Artifacts[0].CreatedAt.Equal(created))++ // A partial struct (Artifacts nil) must not wipe the stored rows.+ require.NoError(t, repo.UpdateMessage(ctx, &types.Message{ID: msg.ID, SessionID: "s1", Content: "edited"}))+ got, err = repo.GetMessage(ctx, "s1", msg.ID)+ require.NoError(t, err)+ require.Equal(t, "edited", got.Content)+ require.Len(t, got.Artifacts, 2)++ // A non-nil list replaces them.+ got.Artifacts = types.MessageArtifacts{testArtifact("c.pptx", "/w/c.pptx", created)}+ require.NoError(t, repo.UpdateMessage(ctx, got))+ listed, err := repo.GetMessagesBySession(ctx, "s1", 1, 10)+ require.NoError(t, err)+ require.Len(t, listed, 1)+ require.Len(t, listed[0].Artifacts, 1)+ require.Equal(t, "c.pptx", listed[0].Artifacts[0].FileName)++ session, err := repo.GetSessionArtifacts(ctx, "s1")+ require.NoError(t, err)+ require.Len(t, session, 1)++ // Soft-deleted messages drop out of the session listing.+ require.NoError(t, repo.DeleteMessage(ctx, "s1", msg.ID))+ session, err = repo.GetSessionArtifacts(ctx, "s1")+ require.NoError(t, err)+ require.Empty(t, session)+}++func TestMessagesWithoutArtifactsLoadAsEmpty(t *testing.T) {+ db := newArtifactTestDB(t)+ repo := NewMessageRepository(db)+ ctx := context.Background()++ msg, err := repo.CreateMessage(ctx, &types.Message{SessionID: "s1", RequestID: "r1", Role: "user"})+ require.NoError(t, err)+ got, err := repo.GetMessage(ctx, "s1", msg.ID)+ require.NoError(t, err)+ require.NotNil(t, got.Artifacts)+ require.Empty(t, got.Artifacts)+}++func TestRecordRestoredArtifactMtimeUpdatesMatchingRows(t *testing.T) {+ db := newArtifactTestDB(t)+ repo := NewMessageRepository(db).(*messageRepository)+ ctx := context.Background()+ created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)++ withHash := func(a types.MessageArtifact, hash string) types.MessageArtifact {+ a.ContentHash = hash+ return a+ }+ v1 := withHash(testArtifact("a.pptx", "/w/a.pptx", created), "hash-a")+ v2 := withHash(testArtifact("a.pptx", "/w/a.pptx", created.Add(time.Hour)), "hash-b")+ v2.URL = "local://blobs/a-v2.pptx"+ msg, err := repo.CreateMessage(ctx, &types.Message{+ SessionID: "s1", RequestID: "r1", Role: "assistant",+ Artifacts: types.MessageArtifacts{v1, v2, testArtifact("b.pptx", "/w/b.pptx", created)},+ })+ require.NoError(t, err)+ originalMod := testArtifact("", "", created).ModTime++ restored := time.Date(2026, 9, 2, 8, 30, 0, 987654321, time.UTC)+ require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "s1", "/w/a.pptx", restored, "hash-a"))+ // An empty hash never matches, so it must change nothing.+ require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "s1", "/w/b.pptx", restored, ""))++ got, err := repo.GetMessage(ctx, "s1", msg.ID)+ require.NoError(t, err)+ require.True(t, got.Artifacts[0].ModTime.Equal(restored), "the version whose content matches gets the mtime")+ require.Equal(t, "hash-a", got.Artifacts[0].ContentHash)+ require.True(t, got.Artifacts[1].ModTime.Equal(originalMod), "other versions at the path stay put")+ require.Equal(t, "hash-b", got.Artifacts[1].ContentHash, "hashes are never rewritten")+ require.True(t, got.Artifacts[2].ModTime.Equal(originalMod), "empty-hash restores are ignored")+}++func TestCreateForkedCopiesArtifactRows(t *testing.T) {+ db := newArtifactTestDB(t)+ sessions := NewSessionRepository(db)+ messages := NewMessageRepository(db)+ ctx := context.Background()+ created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)++ fork := &types.Session{ID: "fork-1", TenantID: 1, UserID: "u1", Title: "fork"}+ copied := []*types.Message{{+ ID: "copy-1", SessionID: "fork-1", Role: "assistant", CreatedAt: created,+ Artifacts: types.MessageArtifacts{testArtifact("a.pptx", "/w/a.pptx", created)},+ }}+ require.NoError(t, sessions.CreateForked(ctx, fork, copied))++ got, err := messages.GetMessage(ctx, "fork-1", "copy-1")+ require.NoError(t, err)+ require.Len(t, got.Artifacts, 1)+ require.Equal(t, "local://blobs/a.pptx", got.Artifacts[0].URL, "the fork points at the same blob")+}++func TestListArtifactLibraryScopesAndGroupsVersions(t *testing.T) {+ db := newArtifactTestDB(t)+ repo := NewMessageRepository(db)+ ctx := context.Background()+ base := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)++ mine := createSession(t, db, &types.Session{TenantID: 7, UserID: "alice", Title: "我的会话"})+ legacy := createSession(t, db, &types.Session{TenantID: 7, Title: "旧会话"})+ bobs := createSession(t, db, &types.Session{TenantID: 7, UserID: "bob", Title: "Bob"})+ otherTenant := createSession(t, db, &types.Session{TenantID: 8, UserID: "alice", Title: "别的空间"})+ maintenance := createSession(t, db, &types.Session{+ TenantID: 7, UserID: "alice", Title: "维护", Description: types.SkillMaintenanceSessionMarker + "x",+ })+ // IM sessions are created without an owner, so they look like legacy+ // tenant-level rows; only the IM mapping tells them apart. A cleared chat+ // keeps its soft-deleted mapping and must stay out as well.+ imChat := createSession(t, db, &types.Session{TenantID: 7, Title: "飞书:张三的私聊"})+ clearedIMChat := createSession(t, db, &types.Session{TenantID: 7, Title: "企微:已清空"})+ embedChat := createSession(t, db, &types.Session{+ TenantID: 7, Title: "网页挂件", Description: types.EmbedSessionMarkerPrefix + "ch-1",+ })+ require.NoError(t, db.Create(&testIMChannelSession{+ ID: "ics-1", SessionID: imChat, Platform: "feishu", TenantID: 7,+ }).Error)+ require.NoError(t, db.Create(&testIMChannelSession{+ ID: "ics-2", SessionID: clearedIMChat, Platform: "wecom", TenantID: 7,+ }).Error)+ require.NoError(t, db.Delete(&testIMChannelSession{ID: "ics-2"}).Error)++ add := func(sessionID string, at time.Time, arts ...types.MessageArtifact) *types.Message {+ m, err := repo.CreateMessage(ctx, &types.Message{+ SessionID: sessionID, RequestID: at.String(), Role: "assistant", CreatedAt: at, Artifacts: arts,+ })+ require.NoError(t, err)+ return m+ }+ // report.pptx regenerated twice in the same session: one item, 2 versions.+ add(mine, base, testArtifact("report.pptx", "/w/report.pptx", base))+ // Each regeneration is persisted as a new blob.+ regenerated := testArtifact("report.pptx", "/w/report.pptx", base.Add(time.Hour))+ regenerated.URL = "local://blobs/report-v2.pptx"+ latest := add(mine, base.Add(time.Hour),+ regenerated,+ types.MessageArtifact{+ URL: "local://blobs/data.csv", FileName: "data.csv", FileType: ".csv",+ SourcePath: "/w/data.csv", CreatedAt: base.Add(2 * time.Hour),+ },+ )+ // A later answer that references old.pptx again stores a second row with+ // the same URL; that is not a new version.+ oldDeck := testArtifact("old.pptx", "/w/old.pptx", base.Add(3*time.Hour))+ add(legacy, base.Add(3*time.Hour), oldDeck)+ add(legacy, base.Add(3*time.Hour+time.Minute), oldDeck)+ add(bobs, base, testArtifact("bob.pptx", "/w/bob.pptx", base))+ add(otherTenant, base, testArtifact("elsewhere.pptx", "/w/e.pptx", base))+ add(maintenance, base, testArtifact("maint.pptx", "/w/m.pptx", base))+ add(imChat, base.Add(5*time.Hour), testArtifact("salary.xlsx", "/w/salary.xlsx", base.Add(5*time.Hour)))+ add(clearedIMChat, base.Add(5*time.Hour), testArtifact("cleared.xlsx", "/w/c.xlsx", base.Add(5*time.Hour)))+ add(embedChat, base.Add(5*time.Hour), testArtifact("widget.pdf", "/w/widget.pdf", base.Add(5*time.Hour)))+ deleted := add(mine, base.Add(4*time.Hour), testArtifact("gone.pptx", "/w/gone.pptx", base.Add(4*time.Hour)))+ require.NoError(t, repo.DeleteMessage(ctx, mine, deleted.ID))++ items, total, err := repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{+ TenantID: 7, UserID: "alice", Page: 1, PageSize: 20,+ })+ require.NoError(t, err)+ require.EqualValues(t, 3, total)+ require.Len(t, items, 3)+ require.Equal(t, []string{"old.pptx", "data.csv", "report.pptx"},+ []string{items[0].FileName, items[1].FileName, items[2].FileName}, "newest first")+ require.Equal(t, "旧会话", items[0].SessionTitle)+ require.Equal(t, 1, items[0].VersionCount, "re-referencing a file does not add a version")++ report := items[2]+ require.Equal(t, 2, report.VersionCount)+ require.Equal(t, latest.ID, report.MessageID, "the latest version wins")+ require.Equal(t, 0, report.Index)+ require.Equal(t, mine, report.SessionID)+ require.Equal(t, 1, items[1].Index, "index is the position inside the owning message")++ // Filters.+ items, total, err = repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{+ TenantID: 7, UserID: "alice", FileTypes: []string{".csv"}, Page: 1, PageSize: 20,+ })+ require.NoError(t, err)+ require.EqualValues(t, 1, total)+ require.Equal(t, "data.csv", items[0].FileName)++ items, total, err = repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{+ TenantID: 7, UserID: "alice", Keyword: "REPORT", Page: 1, PageSize: 20,+ })+ require.NoError(t, err)+ require.EqualValues(t, 1, total)+ require.Equal(t, "report.pptx", items[0].FileName)++ // Paging keeps the total.+ items, total, err = repo.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{+ TenantID: 7, UserID: "alice", Page: 2, PageSize: 2,+ })+ require.NoError(t, err)+ require.EqualValues(t, 3, total)+ require.Len(t, items, 1)+ require.Equal(t, "report.pptx", items[0].FileName)+}diff --git a/internal/application/repository/message_fork_boundary_test.go b/internal/application/repository/message_fork_boundary_test.goindex f96e6c8c5..af6e96ca5 100644--- a/internal/application/repository/message_fork_boundary_test.go+++ b/internal/application/repository/message_fork_boundary_test.go@@ -16,7 +16,7 @@ func newMessageRepositoryForForkTest(t *testing.T) (*messageRepository, *gorm.DBdb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&types.Message{}))+ require.NoError(t, db.AutoMigrate(&types.Message{}, &types.MessageArtifactRecord{}))return &messageRepository{db: db}, db}@@ -108,18 +108,19 @@ func TestRecordRestoredArtifactMtimeOnlyTouchesThisSession(t *testing.T) {SourcePath: "/workspace/output/report.pptx", FileName: "report.pptx",ModTime: oldMod, FileSize: 4, ContentHash: hash,}}- require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{- ID: "parent-msg", SessionID: "parent", Role: "assistant", CreatedAt: at, Artifacts: art,- }).Error)- require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(&types.Message{- ID: "fork-msg", SessionID: "fork-1", Role: "assistant", CreatedAt: at, Artifacts: art,- }).Error)+ seeded := []*types.Message{+ {ID: "parent-msg", SessionID: "parent", Role: "assistant", CreatedAt: at, Artifacts: art},+ {ID: "fork-msg", SessionID: "fork-1", Role: "assistant", CreatedAt: at, Artifacts: art},+ }+ require.NoError(t, db.Session(&gorm.Session{SkipHooks: true}).Create(seeded).Error)+ require.NoError(t, insertMessageArtifacts(db, seeded))require.NoError(t, repo.RecordRestoredArtifactMtime(ctx, "fork-1", "/workspace/output/report.pptx", newMod, hash))- var parent, child types.Message- require.NoError(t, db.Where("id = ?", "parent-msg").First(&parent).Error)- require.NoError(t, db.Where("id = ?", "fork-msg").First(&child).Error)+ parent, err := repo.GetMessage(ctx, "parent", "parent-msg")+ require.NoError(t, err)+ child, err := repo.GetMessage(ctx, "fork-1", "fork-msg")+ require.NoError(t, err)require.True(t, parent.Artifacts[0].ModTime.Equal(oldMod), "parent artifact mtime must stay put")require.True(t, child.Artifacts[0].ModTime.Equal(newMod), "fork artifact mtime should follow the restored sandbox")}diff --git a/internal/application/repository/message_owner_scope_test.go b/internal/application/repository/message_owner_scope_test.goindex b4a29b949..f315cbcd2 100644--- a/internal/application/repository/message_owner_scope_test.go+++ b/internal/application/repository/message_owner_scope_test.go@@ -22,7 +22,7 @@ func newOwnerScopeDB(t *testing.T, name string) (*gorm.DB, map[string]string) {if err != nil {t.Fatalf("open sqlite: %v", err)}- if err := db.AutoMigrate(&types.Session{}, &types.Message{}); err != nil {+ if err := db.AutoMigrate(&types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}); err != nil {t.Fatalf("migrate: %v", err)}sessions := map[string]*types.Session{diff --git a/internal/application/repository/message_search_test.go b/internal/application/repository/message_search_test.goindex fc0dbc299..148e6390c 100644--- a/internal/application/repository/message_search_test.go+++ b/internal/application/repository/message_search_test.go@@ -18,7 +18,7 @@ func newMessageSearchDB(t *testing.T) *gorm.DB {t.Helper()db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&types.Session{}, &types.Message{}))+ require.NoError(t, db.AutoMigrate(&types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}))return db}diff --git a/internal/application/repository/session.go b/internal/application/repository/session.goindex 5384a9e92..b693487bd 100644--- a/internal/application/repository/session.go+++ b/internal/application/repository/session.go@@ -57,6 +57,26 @@ func (r *sessionRepository) Get(ctx context.Context, tenantID uint64, userID strreturn &session, nil}+// webSessionPredicate selects the "web" bucket of the session list: the+// user's own web chats. It excludes IM sessions (any im_channel_sessions+// mapping, including soft-deleted ones), embed-widget sessions (same IM-null+// row) and API-key sessions (surfaced only in the admin-only "api" bucket).+// The user_id NULL check keeps legacy tenant-level web rows visible, since+// "col NOT LIKE ?" is unknown (not true) for NULL.+//+// It expects sessions aliased as s and a+// "LEFT JOIN im_channel_sessions ics ON ics.session_id = s.id".+const webSessionPredicate = "ics.id IS NULL AND (s.description = '' OR s.description NOT LIKE ?) " ++ "AND (s.user_id IS NULL OR (s.user_id NOT LIKE ? AND s.user_id NOT LIKE ?))"++func webSessionPredicateArgs() []any {+ return []any{+ types.EmbedSessionMarkerPrefix + "%",+ types.SessionOwnerAPITenantKeyPrefix + "%",+ types.SessionOwnerAPIExternalUserPrefix + "%",+ }+}+// GetByID retrieves a session by tenant and id without user scoping.func (r *sessionRepository) GetByID(ctx context.Context, tenantID uint64, id string) (*types.Session, error) {var session types.Session@@ -209,17 +229,7 @@ func (r *sessionRepository) QueryPaged(types.SessionOwnerAPIExternalUserPrefix+"%",)case "web":- // User web chats only — exclude embed-widget sessions (same IM-null- // row) and API-key sessions (surfaced only in the admin-only "api"- // bucket). The user_id NULL check keeps legacy tenant-level web rows- // visible, since "col NOT LIKE ?" is unknown (not true) for NULL.- return db.Where(- "ics.id IS NULL AND (s.description = '' OR s.description NOT LIKE ?) "+- "AND (s.user_id IS NULL OR (s.user_id NOT LIKE ? AND s.user_id NOT LIKE ?))",- embedPrefix+"%",- types.SessionOwnerAPITenantKeyPrefix+"%",- types.SessionOwnerAPIExternalUserPrefix+"%",- )+ return db.Where(webSessionPredicate, webSessionPredicateArgs()...)case "embed":return db.Where("ics.id IS NULL AND s.description LIKE ?", embedPrefix+"%")default:@@ -411,8 +421,11 @@ func (r *sessionRepository) CreateForked(if len(messages) == 0 {return nil}- return tx.Session(&gorm.Session{SkipHooks: true}).- CreateInBatches(messages, 100).Error+ if err := tx.Session(&gorm.Session{SkipHooks: true}).+ CreateInBatches(messages, 100).Error; err != nil {+ return err+ }+ return insertMessageArtifacts(tx, messages)})}diff --git a/internal/application/repository/session_fork_test.go b/internal/application/repository/session_fork_test.goindex 77632bad4..1acde9bd6 100644--- a/internal/application/repository/session_fork_test.go+++ b/internal/application/repository/session_fork_test.go@@ -17,7 +17,9 @@ func newSessionRepositoryForForkTest(t *testing.T) (interfaces.SessionRepositorydb, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})require.NoError(t, err)- require.NoError(t, db.AutoMigrate(&types.Session{}, &types.Message{}, &types.ForkSnapshotLease{}))+ require.NoError(t, db.AutoMigrate(+ &types.Session{}, &types.Message{}, &types.MessageArtifactRecord{}, &types.ForkSnapshotLease{},+ ))return NewSessionRepository(db), db}diff --git a/internal/application/service/memory/persistence_consistency_test.go b/internal/application/service/memory/persistence_consistency_test.goindex 121cbdf10..24267df1c 100644--- a/internal/application/service/memory/persistence_consistency_test.go+++ b/internal/application/service/memory/persistence_consistency_test.go@@ -16,7 +16,7 @@ import (func TestMemoryConsistencyRealMessagePaging(t *testing.T) {s, db, tr := newMemoryHarness(t)ctx := enabledCtx(t, tr, 1, "alice")- require.NoError(t, db.AutoMigrate(&types.Message{}))+ require.NoError(t, db.AutoMigrate(&types.Message{}, &types.MessageArtifactRecord{}))at := time.Now().UTC().Truncate(time.Second)for i := 0; i < 85; i++ {require.NoError(t, db.Exec("INSERT INTO messages (id, session_id, role, content, created_at) VALUES (?, ?, ?, ?, ?)", fmt.Sprintf("m%03d", i), "s", "user", "hello", at).Error)diff --git a/internal/application/service/message.go b/internal/application/service/message.goindex 4957ef811..04e1b0ea2 100644--- a/internal/application/service/message.go+++ b/internal/application/service/message.go@@ -522,6 +522,64 @@ func (s *messageService) GetSessionArtifacts(return s.messageRepo.GetSessionArtifacts(ctx, sessionID)}+// artifactLibraryMaxPageSize caps one library page; the page renders a card+// per row, so larger pages only cost bandwidth.+const artifactLibraryMaxPageSize = 100++// ListArtifactLibrary lists the latest version of every artifact in the+// sessions the caller can see. Scope follows ListSessions for its default+// (unfiltered) view: the caller's own sessions plus legacy tenant-level ones.+func (s *messageService) ListArtifactLibrary(+ ctx context.Context, query *types.ArtifactLibraryQuery,+) (*types.PageResult, error) {+ if query == nil {+ query = &types.ArtifactLibraryQuery{}+ }+ query.TenantID = types.MustTenantIDFromContext(ctx)+ query.UserID = types.SessionOwnerIDFromContext(ctx)+ pagination := &types.Pagination{Page: query.Page, PageSize: query.PageSize}+ query.Page = pagination.GetPage()+ query.PageSize = min(pagination.GetPageSize(), artifactLibraryMaxPageSize)+ pagination.PageSize = query.PageSize+ query.FileTypes = normalizeArtifactFileTypes(query.FileTypes)++ items, total, err := s.messageRepo.ListArtifactLibrary(ctx, query)+ if err != nil {+ logger.ErrorWithFields(ctx, err, map[string]interface{}{+ "tenant_id": query.TenantID,+ "user_id": query.UserID,+ })+ return nil, err+ }+ for _, item := range items {+ if handle, ok := types.ParseResourcePath(item.URL); ok {+ item.Handle = types.BuildResourcePath(handle)+ }+ }+ return types.NewPageResult(total, pagination, items), nil+}++// normalizeArtifactFileTypes lower-cases extensions and adds the leading dot+// the collector stores ("pdf" and ".PDF" both become ".pdf").+func normalizeArtifactFileTypes(in []string) []string {+ out := make([]string, 0, len(in))+ seen := make(map[string]bool, len(in))+ for _, raw := range in {+ ext := strings.ToLower(strings.TrimSpace(raw))+ if ext == "" {+ continue+ }+ if !strings.HasPrefix(ext, ".") {+ ext = "." + ext+ }+ if !seen[ext] {+ seen[ext] = true+ out = append(out, ext)+ }+ }+ return out+}+// ─────────────────────────────────────────────────────────────────────────────// Message Search (Hybrid: Keyword + KB Vector Search)// ─────────────────────────────────────────────────────────────────────────────diff --git a/internal/application/service/message_artifact_library_test.go b/internal/application/service/message_artifact_library_test.gonew file mode 100644index 000000000..d620a7566--- /dev/null+++ b/internal/application/service/message_artifact_library_test.go@@ -0,0 +1,53 @@+package service++import (+ "context"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/stretchr/testify/require"+)++type libraryMessageRepo struct {+ interfaces.MessageRepository+ query *types.ArtifactLibraryQuery+ items []*types.ArtifactLibraryItem+}++func (r *libraryMessageRepo) ListArtifactLibrary(+ _ context.Context, q *types.ArtifactLibraryQuery,+) ([]*types.ArtifactLibraryItem, int64, error) {+ r.query = q+ return r.items, int64(len(r.items)), nil+}++func TestListArtifactLibraryScopesToCallerAndNormalizesQuery(t *testing.T) {+ handle := "resource://dHZ_fFslfs0GgJGaJZGjGA"+ repo := &libraryMessageRepo{items: []*types.ArtifactLibraryItem{+ {FileName: "deck.pptx", URL: handle},+ {FileName: "raw.csv", URL: "local://tenant/raw.csv"},+ }}+ s := &messageService{messageRepo: repo}+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))+ ctx = context.WithValue(ctx, types.UserIDContextKey, "alice")++ result, err := s.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{+ TenantID: 99,+ UserID: "mallory",+ FileTypes: []string{"PDF", " .pptx ", "pdf", ""},+ PageSize: 5000,+ })+ require.NoError(t, err)++ require.Equal(t, uint64(7), repo.query.TenantID, "tenant comes from the context, not the request")+ require.Equal(t, "alice", repo.query.UserID, "owner comes from the context, not the request")+ require.Equal(t, []string{".pdf", ".pptx"}, repo.query.FileTypes)+ require.Equal(t, 1, repo.query.Page)+ require.Equal(t, artifactLibraryMaxPageSize, repo.query.PageSize)+ require.Equal(t, artifactLibraryMaxPageSize, result.PageSize)++ items := result.Data.([]*types.ArtifactLibraryItem)+ require.Equal(t, handle, items[0].Handle)+ require.Empty(t, items[1].Handle, "non-resource URLs never leak as handles")+}diff --git a/internal/application/service/session_fork.go b/internal/application/service/session_fork.goindex 67d9a139a..92303f485 100644--- a/internal/application/service/session_fork.go+++ b/internal/application/service/session_fork.go@@ -468,9 +468,9 @@ func historyThroughForkPoint(listed []*types.Message, forkPoint *types.Message)// per original value so a user/assistant pair stays paired inside the fork// without colliding with the parent in search partner lookups.//-// Copies deliberately keep their Artifacts and Attachments. Artifact URLs are-// persisted on the message row, so the forked session's 产物 tab can list and-// download the same files. Attachment storage handles live in+// Copies deliberately keep their Artifacts and Attachments. CreateForked+// writes the copied artifact rows (same storage URLs) under the new message+// IDs, so the forked session's 产物 tab can list and download the same files. Attachment storage handles live in// temporary_documents (still scoped to the parent session) and are resolved// by ID at preview and staging time when the copied messages reference them.func copyMessagesInto(newSessionID string, history []*types.Message) []*types.Message {diff --git a/internal/database/migration_sqlite_message_artifacts_test.go b/internal/database/migration_sqlite_message_artifacts_test.gonew file mode 100644index 000000000..0d28c731d--- /dev/null+++ b/internal/database/migration_sqlite_message_artifacts_test.go@@ -0,0 +1,135 @@+package database++import (+ "database/sql"+ "encoding/json"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/stretchr/testify/require"+)++// TestSQLiteMessageArtifactsBackfillAndRollback upgrades a v22 database that+// still keeps artifacts on messages.artifacts, checks 000023 copies them into+// message_artifacts, then replays the down migration and checks the JSON+// column is rebuilt from the table in a shape Go can decode.+func TestSQLiteMessageArtifactsBackfillAndRollback(t *testing.T) {+ repoRoot := sqliteRepoRoot(t)++ legacyRoot := copySQLiteMigrationsThrough(t, repoRoot, 22)+ chdirAndRestore(t, legacyRoot)+ dbPath := filepath.Join(t.TempDir(), "artifacts.db")+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))++ db := openSQLiteDB(t, dbPath)+ legacy := `[+ {"url":"local://a/report.pptx","file_name":"report.pptx","file_type":".pptx","file_size":2048,+ "content_hash":"abc","source_path":"/workspace/report.pptx",+ "mod_time":"2026-09-01T10:00:00.123456789+08:00","created_at":"2026-09-01T10:00:05+08:00"},+ {"url":"local://a/chart.png","file_name":"chart.png","file_type":".png","file_size":10,+ "source_path":"/workspace/chart.png","mod_time":"2026-09-01T10:00:00Z","created_at":"2026-09-01T02:00:06Z"}+ ]`+ _, err := db.Exec(+ `INSERT INTO messages (id, request_id, session_id, role, content, artifacts, created_at)+ VALUES ('msg-1', 'req-1', 'sess-1', 'assistant', 'done', ?, '2026-09-01 02:00:00')`,+ legacy,+ )+ require.NoError(t, err)+ _, err = db.Exec(+ `INSERT INTO messages (id, request_id, session_id, role, content, artifacts)+ VALUES ('msg-2', 'req-2', 'sess-1', 'user', 'hi', '[]')`,+ )+ require.NoError(t, err)+ // Malformed values must fall back instead of failing the migration.+ _, err = db.Exec(+ `INSERT INTO messages (id, request_id, session_id, role, content, artifacts, created_at)+ VALUES ('msg-3', 'req-3', 'sess-1', 'assistant', 'dirty', ?, '2026-09-02 00:00:00')`,+ `[{"file_name":"dirty.bin","file_size":"12.5x","created_at":"garbage"}, 7, "x"]`,+ )+ require.NoError(t, err)+ require.NoError(t, db.Close())++ chdirAndRestore(t, repoRoot)+ require.NoError(t, RunMigrationsWithOptions("sqlite3://unused", MigrationOptions{SQLiteDBPath: dbPath}))+ db = openSQLiteDB(t, dbPath)++ type row struct {+ position int+ fileName string+ fileSize int64+ sourcePath string+ modTime string+ createdAt time.Time+ }+ rows, err := db.Query(+ `SELECT position, file_name, file_size, source_path, mod_time, created_at+ FROM message_artifacts WHERE message_id = 'msg-1' ORDER BY position`,+ )+ require.NoError(t, err)+ var got []row+ for rows.Next() {+ var r row+ require.NoError(t, rows.Scan(&r.position, &r.fileName, &r.fileSize, &r.sourcePath, &r.modTime, &r.createdAt))+ got = append(got, r)+ }+ require.NoError(t, rows.Err())+ require.NoError(t, rows.Close())++ require.Len(t, got, 2)+ require.Equal(t, 0, got[0].position)+ require.Equal(t, "report.pptx", got[0].fileName)+ require.Equal(t, int64(2048), got[0].fileSize)+ require.Equal(t, "/workspace/report.pptx", got[0].sourcePath)+ require.Equal(t, "2026-09-01T10:00:00.123456789+08:00", got[0].modTime, "mod_time keeps the exact RFC 3339 text")+ wantCreated, _ := time.Parse(time.RFC3339, "2026-09-01T02:00:05Z")+ require.True(t, got[0].createdAt.Equal(wantCreated), "created_at normalised to UTC: %v", got[0].createdAt)+ require.Equal(t, 1, got[1].position)+ require.Equal(t, "chart.png", got[1].fileName)++ var dirtySize int64+ var dirtyCreated time.Time+ require.NoError(t, db.QueryRow(+ `SELECT file_size, created_at FROM message_artifacts WHERE message_id = 'msg-3'`,+ ).Scan(&dirtySize, &dirtyCreated))+ require.EqualValues(t, 12, dirtySize, "SQLite CAST keeps the numeric prefix")+ require.True(t, dirtyCreated.Equal(time.Date(2026, 9, 2, 0, 0, 0, 0, time.UTC)),+ "an unparseable created_at falls back to the message time: %v", dirtyCreated)++ var userRows int+ require.NoError(t, db.QueryRow(`SELECT COUNT(*) FROM message_artifacts WHERE message_id = 'msg-2'`).Scan(&userRows))+ require.Zero(t, userRows)++ // The legacy column is cleared once copied, so history loads (SELECT *)+ // no longer read a stale duplicate; rows without artifacts are untouched.+ var legacy1, legacy2 sql.NullString+ require.NoError(t, db.QueryRow(`SELECT artifacts FROM messages WHERE id = 'msg-1'`).Scan(&legacy1))+ require.NoError(t, db.QueryRow(`SELECT artifacts FROM messages WHERE id = 'msg-2'`).Scan(&legacy2))+ require.False(t, legacy1.Valid, "copied artifacts are cleared from messages.artifacts")+ require.Equal(t, "[]", legacy2.String)++ // Rollback rebuilds the legacy column from the table.+ down, err := os.ReadFile(filepath.Join(repoRoot, "migrations", "sqlite", "000023_message_artifacts_table.down.sql"))+ require.NoError(t, err)+ _, err = db.Exec(string(down))+ require.NoError(t, err)+ require.False(t, sqliteTableExists(t, db, "message_artifacts"))++ var restored string+ require.NoError(t, db.QueryRow(`SELECT artifacts FROM messages WHERE id = 'msg-1'`).Scan(&restored))+ var decoded []struct {+ FileName string `json:"file_name"`+ FileSize int64 `json:"file_size"`+ ModTime time.Time `json:"mod_time"`+ CreatedAt time.Time `json:"created_at"`+ }+ wantMod, _ := time.Parse(time.RFC3339Nano, "2026-09-01T10:00:00.123456789+08:00")+ require.NoError(t, json.Unmarshal([]byte(restored), &decoded))+ require.Len(t, decoded, 2)+ require.Equal(t, "report.pptx", decoded[0].FileName)+ require.Equal(t, int64(2048), decoded[0].FileSize)+ require.True(t, decoded[0].CreatedAt.Equal(wantCreated))+ require.True(t, decoded[0].ModTime.Equal(wantMod), "rollback keeps nanosecond mtime")+ require.Equal(t, "chart.png", decoded[1].FileName)+}diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.goindex 6ea1da70b..bf7123184 100644--- a/internal/database/migration_sqlite_versioned_schema_test.go+++ b/internal/database/migration_sqlite_versioned_schema_test.go@@ -14,7 +14,8 @@ import (// versionedSQLiteTables is the set of tables that SQLite migrations must// create to stay in sync with the versioned (PostgreSQL) migrations:// 000041 task queue, 000053 system settings, 000055 processing spans,-// 000063 knowledge multi-tags, 000093 browser authorization.+// 000063 knowledge multi-tags, 000093 browser authorization, 000103 message+// artifacts.var versionedSQLiteTables = []string{"memory_extraction_sessions","task_pending_ops",@@ -27,6 +28,7 @@ var versionedSQLiteTables = []string{"browser_task_interruptions","fork_snapshot_leases","mcp_endpoints",+ "message_artifacts",}// versionedSQLiteColumns maps each existing table to the columns that the@@ -46,7 +48,7 @@ var versionedSQLiteColumns = map[string][]string{"mcp_tool_approvals": {"enabled"}, // 000091}-const expectedSQLiteMigrationVersion = 22+const expectedSQLiteMigrationVersion = 23func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {repoRoot := sqliteRepoRoot(t)diff --git a/internal/handler/session/artifact_library.go b/internal/handler/session/artifact_library.gonew file mode 100644index 000000000..4f5e71873--- /dev/null+++ b/internal/handler/session/artifact_library.go@@ -0,0 +1,61 @@+package session++import (+ "net/http"+ "strings"++ "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/logger"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/gin-gonic/gin"+)++// ListArtifactLibrary godoc+// @Summary 列出我的产物+// @Description 跨会话列出当前用户可见会话中技能生成的文件,每个文件只返回最新版本(不含存储 URL)+// @Tags 会话+// @Produce json+// @Param keyword query string false "按文件名过滤"+// @Param file_types query string false "逗号分隔的扩展名,如 .pdf,.pptx"+// @Param page query int false "页码"+// @Param page_size query int false "每页数量(最大 100)"+// @Success 200 {object} map[string]interface{}+// @Security Bearer+// @Security ApiKeyAuth+// @Router /artifacts [get]+//+// Items carry session_id, message_id and index so the client downloads+// through the per-session endpoint, which re-runs the ownership check.+func (h *Handler) ListArtifactLibrary(c *gin.Context) {+ ctx := c.Request.Context()++ var pagination types.Pagination+ if err := c.ShouldBindQuery(&pagination); err != nil {+ _ = c.Error(errors.NewBadRequestError(err.Error()))+ return+ }+ var fileTypes []string+ if raw := c.Query("file_types"); raw != "" {+ fileTypes = strings.Split(raw, ",")+ }++ result, err := h.messageService.ListArtifactLibrary(ctx, &types.ArtifactLibraryQuery{+ Keyword: c.Query("keyword"),+ FileTypes: fileTypes,+ Page: pagination.Page,+ PageSize: pagination.PageSize,+ })+ if err != nil {+ logger.Errorf(ctx, "list artifact library failed: %v", err)+ _ = c.Error(errors.NewInternalServerError(err.Error()))+ return+ }++ c.JSON(http.StatusOK, gin.H{+ "success": true,+ "data": result.Data,+ "total": result.Total,+ "page": result.Page,+ "page_size": result.PageSize,+ })+}diff --git a/internal/router/routes_chat.go b/internal/router/routes_chat.goindex 5a9606ce2..6450a60d9 100644--- a/internal/router/routes_chat.go+++ b/internal/router/routes_chat.go@@ -109,6 +109,14 @@ func RegisterSessionRoutes(sessions.GET("/:id/messages/:message_id/artifacts", handler.ListMessageArtifacts)sessions.GET("/:id/messages/:message_id/artifacts/:index/download", handler.DownloadMessageArtifact)}++ // Cross-session artifact library. Same guards as /sessions: the rows come+ // from the caller's own sessions, and downloads go back through the+ // per-session endpoint above.+ artifacts := g.apiKeyGroup(r.Group("/artifacts", g.Viewer()), apiKeyChat(apiKeyFullAccess()))+ {+ artifacts.GET("", handler.ListArtifactLibrary)+ }}// RegisterChatRoutes 注册路由。Chat endpoints are tenant-member usagediff --git a/internal/types/interfaces/message.go b/internal/types/interfaces/message.goindex 195c60fbe..dbed461d4 100644--- a/internal/types/interfaces/message.go+++ b/internal/types/interfaces/message.go@@ -63,6 +63,11 @@ type MessageService interface {// the frontend "download files generated in this session" drawer and// to clean up storage blobs on session deletion.GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error)++ // ListArtifactLibrary lists the latest version of every artifact across+ // the caller's sessions, newest first. Tenant and owner scope come from+ // ctx; query.TenantID and query.UserID are overwritten.+ ListArtifactLibrary(ctx context.Context, query *types.ArtifactLibraryQuery) (*types.PageResult, error)}// MessageRepository defines the message repository interface@@ -128,6 +133,11 @@ type MessageRepository interface {// cheap even for long conversations. Empty slice + nil error means the// session has no artifacts yet (never an error).GetSessionArtifacts(ctx context.Context, sessionID string) (types.MessageArtifacts, error)+ // ListArtifactLibrary returns one page of the latest artifact versions in+ // the sessions query.TenantID / query.UserID can see, plus the total.+ ListArtifactLibrary(+ ctx context.Context, query *types.ArtifactLibraryQuery,+ ) ([]*types.ArtifactLibraryItem, int64, error)// GetSessionAttachments returns every user-uploaded attachment recorded in// the session. Implementations should project only the attachments column.GetSessionAttachments(ctx context.Context, sessionID string) (types.MessageAttachments, error)diff --git a/internal/types/message.go b/internal/types/message.goindex e143b064f..32f7db04b 100644--- a/internal/types/message.go+++ b/internal/types/message.go@@ -363,7 +363,11 @@ type Message struct {// Skill-generated files produced during this assistant turn (assistant messages only).// Populated by ArtifactCollector after the sandbox finishes, referenced by the// artifact download endpoint. Empty for user messages and turns without skills.- Artifacts MessageArtifacts `json:"artifacts,omitempty" gorm:"type:jsonb;column:artifacts"`+ //+ // Stored in the message_artifacts table, not on the message row: the message+ // repository loads it with every message it returns and writes it whenever it+ // is non-nil on create or update. A nil slice leaves the stored rows alone.+ Artifacts MessageArtifacts `json:"artifacts,omitempty" gorm:"-"`// Whether message generation is completeIsCompleted bool `json:"is_completed"`// Whether this response is a fallback (no knowledge base match found)diff --git a/internal/types/message_artifact.go b/internal/types/message_artifact.gonew file mode 100644index 000000000..7e68b8009--- /dev/null+++ b/internal/types/message_artifact.go@@ -0,0 +1,132 @@+package types++import (+ "time"++ "github.com/google/uuid"+)++// MessageArtifactRecord is one row of message_artifacts: a MessageArtifact+// plus the message it belongs to and its position in that message's list.+// Position is the index the download endpoint addresses the file by.+type MessageArtifactRecord struct {+ ID string `gorm:"type:varchar(36);primaryKey"`+ SessionID string `gorm:"column:session_id"`+ MessageID string `gorm:"column:message_id"`+ Position int `gorm:"column:position"`+ URL string `gorm:"column:url"`+ FileName string `gorm:"column:file_name"`+ FileType string `gorm:"column:file_type"`+ FileSize int64 `gorm:"column:file_size"`+ ContentHash string `gorm:"column:content_hash"`+ SourcePath string `gorm:"column:source_path"`+ // ModTime is RFC 3339 text rather than a timestamp column: the collector+ // matches files on (source path, mtime) at nanosecond precision, which+ // PostgreSQL timestamps would truncate to microseconds. Empty means zero.+ ModTime string `gorm:"column:mod_time"`+ CreatedAt time.Time `gorm:"column:created_at"`+}++// TableName implements gorm's tabler.+func (MessageArtifactRecord) TableName() string { return "message_artifacts" }++// NewMessageArtifactRecords turns a message's artifact list into table rows.+//+// CreatedAt is stored in UTC: SQLite compares DATETIME values as text, so+// mixing zones would break ORDER BY created_at. A zero CreatedAt (an artifact+// built outside the collector) falls back to now, matching what the collector+// would have stamped.+func NewMessageArtifactRecords(sessionID, messageID string, list MessageArtifacts) []MessageArtifactRecord {+ if len(list) == 0 {+ return nil+ }+ now := time.Now().UTC()+ rows := make([]MessageArtifactRecord, 0, len(list))+ for i, a := range list {+ created := a.CreatedAt.UTC()+ if a.CreatedAt.IsZero() {+ created = now+ }+ rows = append(rows, MessageArtifactRecord{+ ID: uuid.New().String(),+ SessionID: sessionID,+ MessageID: messageID,+ Position: i,+ URL: a.URL,+ FileName: a.FileName,+ FileType: a.FileType,+ FileSize: a.FileSize,+ ContentHash: a.ContentHash,+ SourcePath: a.SourcePath,+ ModTime: FormatArtifactModTime(a.ModTime),+ CreatedAt: created,+ })+ }+ return rows+}++// FormatArtifactModTime encodes an mtime for message_artifacts.mod_time.+func FormatArtifactModTime(t time.Time) string {+ if t.IsZero() {+ return ""+ }+ return t.Format(time.RFC3339Nano)+}++// ParseArtifactModTime decodes message_artifacts.mod_time; anything+// unparseable reads as the zero time, which only costs the collector a hash.+func ParseArtifactModTime(s string) time.Time {+ if s == "" {+ return time.Time{}+ }+ t, err := time.Parse(time.RFC3339Nano, s)+ if err != nil {+ return time.Time{}+ }+ return t+}++// Artifact converts the row back to the value carried on Message.Artifacts.+func (r MessageArtifactRecord) Artifact() MessageArtifact {+ return MessageArtifact{+ URL: r.URL,+ FileName: r.FileName,+ FileType: r.FileType,+ FileSize: r.FileSize,+ ContentHash: r.ContentHash,+ SourcePath: r.SourcePath,+ ModTime: ParseArtifactModTime(r.ModTime),+ CreatedAt: r.CreatedAt,+ }+}++// ArtifactLibraryQuery lists the artifacts across every session the caller can+// see. TenantID and UserID are filled by the service from the request context.+type ArtifactLibraryQuery struct {+ TenantID uint64+ UserID string+ // Keyword matches the file name, case-insensitively.+ Keyword string+ // FileTypes restricts results to these extensions (".pdf", ".pptx", ...).+ FileTypes []string+ Page int+ PageSize int+}++// ArtifactLibraryItem is the latest version of one file in one session.+// Versions are the artifacts that share a session and sandbox source path:+// regenerating report.pptx three times is one item with VersionCount 3.+type ArtifactLibraryItem struct {+ SessionID string `json:"session_id" gorm:"column:session_id"`+ SessionTitle string `json:"session_title" gorm:"column:session_title"`+ MessageID string `json:"message_id" gorm:"column:message_id"`+ Index int `json:"index" gorm:"column:position"`+ URL string `json:"-" gorm:"column:url"`+ Handle string `json:"handle,omitempty" gorm:"-"`+ FileName string `json:"file_name" gorm:"column:file_name"`+ FileType string `json:"file_type" gorm:"column:file_type"`+ FileSize int64 `json:"file_size" gorm:"column:file_size"`+ SourcePath string `json:"source_path" gorm:"column:source_path"`+ CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`+ VersionCount int `json:"version_count" gorm:"column:version_count"`+}diff --git a/migrations/sqlite/000023_message_artifacts_table.down.sql b/migrations/sqlite/000023_message_artifacts_table.down.sqlnew file mode 100644index 000000000..83bfa6e28--- /dev/null+++ b/migrations/sqlite/000023_message_artifacts_table.down.sql@@ -0,0 +1,27 @@+-- Restore messages.artifacts from the table before dropping it, so files+-- generated after the upgrade survive a rollback. created_at is normalised to+-- RFC 3339 so Go can decode the restored JSON; mod_time is already RFC 3339.+UPDATE messages+SET artifacts = (+ SELECT json_group_array(json(item))+ FROM (+ SELECT json_object(+ 'url', url,+ 'file_name', file_name,+ 'file_type', file_type,+ 'file_size', file_size,+ 'content_hash', content_hash,+ 'source_path', source_path,+ 'mod_time', NULLIF(mod_time, ''),+ 'created_at', strftime('%Y-%m-%dT%H:%M:%fZ', created_at)+ ) AS item+ FROM message_artifacts+ WHERE message_artifacts.message_id = messages.id+ ORDER BY position+ )+)+WHERE id IN (SELECT message_id FROM message_artifacts);++DROP INDEX IF EXISTS idx_message_artifacts_session_created;+DROP INDEX IF EXISTS idx_message_artifacts_message_position;+DROP TABLE IF EXISTS message_artifacts;diff --git a/migrations/sqlite/000023_message_artifacts_table.up.sql b/migrations/sqlite/000023_message_artifacts_table.up.sqlnew file mode 100644index 000000000..e337712eb--- /dev/null+++ b/migrations/sqlite/000023_message_artifacts_table.up.sql@@ -0,0 +1,59 @@+-- Mirrors versioned migration 000103_message_artifacts_table:+-- skill-generated files move out of messages.artifacts into their own table,+-- which becomes the only source of truth. After the backfill the legacy column+-- is cleared (message loads still SELECT *) but kept; the down migration+-- rebuilds it from the table.++CREATE TABLE IF NOT EXISTS message_artifacts (+ id VARCHAR(36) PRIMARY KEY,+ session_id VARCHAR(36) NOT NULL,+ message_id VARCHAR(36) NOT NULL,+ position INTEGER NOT NULL,+ url TEXT NOT NULL DEFAULT '',+ file_name TEXT NOT NULL DEFAULT '',+ file_type VARCHAR(32) NOT NULL DEFAULT '',+ file_size INTEGER NOT NULL DEFAULT 0,+ content_hash VARCHAR(64) NOT NULL DEFAULT '',+ source_path TEXT NOT NULL DEFAULT '',+ mod_time VARCHAR(64) NOT NULL DEFAULT '',+ created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP+);++CREATE UNIQUE INDEX IF NOT EXISTS idx_message_artifacts_message_position+ ON message_artifacts (message_id, position);+CREATE INDEX IF NOT EXISTS idx_message_artifacts_session_created+ ON message_artifacts (session_id, created_at);++-- mod_time is kept as the RFC 3339 text Go wrote (nanosecond precision; the+-- collector matches files on it). created_at is an ORDER BY key compared as+-- text, so it is normalised to UTC in the layout the repository writes.+INSERT OR IGNORE INTO message_artifacts (+ id, session_id, message_id, position, url, file_name, file_type, file_size,+ content_hash, source_path, mod_time, created_at+)+SELECT+ lower(hex(randomblob(4)) || '-' || hex(randomblob(2)) || '-' || hex(randomblob(2)) || '-' ||+ hex(randomblob(2)) || '-' || hex(randomblob(6))),+ m.session_id,+ m.id,+ CAST(a.key AS INTEGER),+ COALESCE(json_extract(a.value, '$.url'), ''),+ COALESCE(json_extract(a.value, '$.file_name'), ''),+ substr(COALESCE(json_extract(a.value, '$.file_type'), ''), 1, 32),+ COALESCE(CAST(json_extract(a.value, '$.file_size') AS INTEGER), 0),+ substr(COALESCE(json_extract(a.value, '$.content_hash'), ''), 1, 64),+ COALESCE(json_extract(a.value, '$.source_path'), ''),+ substr(COALESCE(json_extract(a.value, '$.mod_time'), ''), 1, 64),+ COALESCE(+ strftime('%Y-%m-%d %H:%M:%f+00:00', NULLIF(json_extract(a.value, '$.created_at'), '')),+ strftime('%Y-%m-%d %H:%M:%f+00:00', m.created_at),+ strftime('%Y-%m-%d %H:%M:%f+00:00', 'now')+ )+FROM messages m, json_each(+ CASE WHEN json_valid(m.artifacts) AND json_type(m.artifacts) = 'array' THEN m.artifacts ELSE '[]' END+) a+WHERE a.type = 'object';++-- Only rows that carried artifacts; '[]' rows are left as they are.+UPDATE messages SET artifacts = NULL+WHERE artifacts IS NOT NULL AND artifacts <> '[]';diff --git a/migrations/versioned/000103_message_artifacts_table.down.sql b/migrations/versioned/000103_message_artifacts_table.down.sqlnew file mode 100644index 000000000..108bb99a1--- /dev/null+++ b/migrations/versioned/000103_message_artifacts_table.down.sql@@ -0,0 +1,28 @@+-- Restore messages.artifacts from the table before dropping it, so files+-- generated after the upgrade survive a rollback.+UPDATE messages m+SET artifacts = agg.artifacts+FROM (+ SELECT+ message_id,+ jsonb_agg(+ jsonb_build_object(+ 'url', url,+ 'file_name', file_name,+ 'file_type', file_type,+ 'file_size', file_size,+ 'content_hash', content_hash,+ 'source_path', source_path,+ 'mod_time', NULLIF(mod_time, ''),+ 'created_at', created_at+ )+ ORDER BY position+ ) AS artifacts+ FROM message_artifacts+ GROUP BY message_id+) agg+WHERE m.id = agg.message_id;++DROP INDEX IF EXISTS idx_message_artifacts_session_created;+DROP INDEX IF EXISTS idx_message_artifacts_message_position;+DROP TABLE IF EXISTS message_artifacts;diff --git a/migrations/versioned/000103_message_artifacts_table.up.sql b/migrations/versioned/000103_message_artifacts_table.up.sqlnew file mode 100644index 000000000..1edfd1fbc--- /dev/null+++ b/migrations/versioned/000103_message_artifacts_table.up.sql@@ -0,0 +1,86 @@+-- Migration: 000103_message_artifacts_table+-- Skill-generated files move out of the messages.artifacts JSONB column into+-- their own table so they can be listed across sessions (the artifact library)+-- without expanding every message's JSON. The table becomes the only source of+-- truth. After the backfill the legacy column is cleared (message loads still+-- SELECT *, so a stale copy would be read on every history load) but kept, so+-- instances still on the old binary during a rolling upgrade keep working. The+-- down migration rebuilds the column from this table.+DO $$ BEGIN RAISE NOTICE '[Migration 000103] Creating message_artifacts table'; END $$;++CREATE TABLE IF NOT EXISTS message_artifacts (+ id VARCHAR(36) PRIMARY KEY DEFAULT uuid_generate_v4(),+ session_id VARCHAR(36) NOT NULL,+ message_id VARCHAR(36) NOT NULL,+ position INTEGER NOT NULL,+ url TEXT NOT NULL DEFAULT '',+ file_name TEXT NOT NULL DEFAULT '',+ file_type VARCHAR(32) NOT NULL DEFAULT '',+ file_size BIGINT NOT NULL DEFAULT 0,+ content_hash VARCHAR(64) NOT NULL DEFAULT '',+ source_path TEXT NOT NULL DEFAULT '',+ mod_time VARCHAR(64) NOT NULL DEFAULT '',+ created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP+);++CREATE UNIQUE INDEX IF NOT EXISTS idx_message_artifacts_message_position+ ON message_artifacts (message_id, position);+CREATE INDEX IF NOT EXISTS idx_message_artifacts_session_created+ ON message_artifacts (session_id, created_at);++COMMENT ON TABLE message_artifacts IS 'Files a skill script produced during an assistant turn, one row per file';+COMMENT ON COLUMN message_artifacts.position IS 'Zero-based position within the owning message; the download API addresses files by it';+COMMENT ON COLUMN message_artifacts.url IS 'Storage or resource:// URL; never returned to clients';+COMMENT ON COLUMN message_artifacts.mod_time IS 'Sandbox mtime as RFC 3339 text; kept at nanosecond precision because the collector matches files on it';+COMMENT ON COLUMN message_artifacts.source_path IS 'Absolute path inside the sandbox; repeated paths in a session are versions of one file';++DO $$ BEGIN RAISE NOTICE '[Migration 000103] Backfilling message_artifacts from messages.artifacts'; END $$;++-- A single malformed value (a numeric string, an impossible date) must not fail+-- the whole migration, so casts go through session-scoped helpers that return+-- NULL instead of raising; pg_temp objects vanish with the connection.+CREATE OR REPLACE FUNCTION pg_temp.wk_try_bigint(v TEXT) RETURNS BIGINT+LANGUAGE plpgsql IMMUTABLE AS $$+BEGIN+ RETURN v::NUMERIC::BIGINT;+EXCEPTION WHEN others THEN+ RETURN NULL;+END $$;++CREATE OR REPLACE FUNCTION pg_temp.wk_try_timestamptz(v TEXT) RETURNS TIMESTAMPTZ+LANGUAGE plpgsql IMMUTABLE AS $$+BEGIN+ RETURN v::TIMESTAMPTZ;+EXCEPTION WHEN others THEN+ RETURN NULL;+END $$;++INSERT INTO message_artifacts (+ session_id, message_id, position, url, file_name, file_type, file_size,+ content_hash, source_path, mod_time, created_at+)+SELECT+ m.session_id,+ m.id,+ (a.ord - 1)::INTEGER,+ COALESCE(a.elem ->> 'url', ''),+ COALESCE(a.elem ->> 'file_name', ''),+ LEFT(COALESCE(a.elem ->> 'file_type', ''), 32),+ COALESCE(pg_temp.wk_try_bigint(a.elem ->> 'file_size'), 0),+ LEFT(COALESCE(a.elem ->> 'content_hash', ''), 64),+ COALESCE(a.elem ->> 'source_path', ''),+ LEFT(COALESCE(a.elem ->> 'mod_time', ''), 64),+ COALESCE(pg_temp.wk_try_timestamptz(a.elem ->> 'created_at'), m.created_at, CURRENT_TIMESTAMP)+FROM messages m+CROSS JOIN LATERAL jsonb_array_elements(+ CASE WHEN jsonb_typeof(m.artifacts) = 'array' THEN m.artifacts ELSE '[]'::jsonb END+) WITH ORDINALITY AS a(elem, ord)+WHERE jsonb_typeof(a.elem) = 'object'+ON CONFLICT (message_id, position) DO NOTHING;++DO $$ BEGIN RAISE NOTICE '[Migration 000103] Clearing legacy messages.artifacts'; END $$;++-- Only rows that carried artifacts; rewriting every '[]' row would touch the+-- whole messages table for nothing.+UPDATE messages SET artifacts = NULL+WHERE artifacts IS NOT NULL AND artifacts <> '[]'::jsonb;diff --git a/website-docs/04-api/02-api-chat.md b/website-docs/04-api/02-api-chat.mdindex cb7dce46e..4adf8c8f2 100644--- a/website-docs/04-api/02-api-chat.md+++ b/website-docs/04-api/02-api-chat.md@@ -385,6 +385,23 @@ curl "$BASE/api/v1/sessions/session-1/messages/message-1/artifacts/0/download" \-H "Authorization: Bearer $TOKEN" -o result.pdf```+### 跨会话产物列表++`GET /api/v1/artifacts` 列出当前用户网页对话中的所有生成文件,供首页侧栏「产物」页使用。范围与会话列表的 `source=web` 一致:本人会话及历史上无归属的租户级网页会话;IM 渠道、网页挂件(embed)和 API Key 会话一律不含,即使 IM 会话在库中没有归属人。同一会话中 `source_path` 相同的文件视为同一文件的多个版本,只返回最新一版,`version_count` 给出版本数。已删除的会话或消息中的文件不返回。权限要求与上表相同。++| 参数 | 说明 |+| --- | --- |+| `keyword` | 按文件名过滤,不区分大小写 |+| `file_types` | 逗号分隔的扩展名,如 `.pdf,.pptx`(可省略点号) |+| `page` / `page_size` | 分页,`page_size` 最大 100,默认 20 |++响应 `{success, data:[LibraryArtifact], total, page, page_size}`,按生成时间倒序。LibraryArtifact 字段:session_id、session_title、message_id、index、handle(可选)、file_name、file_type、file_size、source_path、created_at、version_count。下载时用其中的 session_id、message_id、index 调用上表的下载接口。++```bash+curl "$BASE/api/v1/artifacts?file_types=.pptx,.pdf&keyword=报告&page=1&page_size=30" \+ -H "Authorization: Bearer $TOKEN"+```+### 回答中的图片和文件引用`GET /api/v1/sessions/:id/messages/:message_id/files?file_path=...` 是消息级鉴权代理。file_path 传该消息引用的资源句柄或受支持的存储引用,客户端应 URL 编码。后端校验消息访问权、资源与消息的绑定及知识库/共享 Agent 的当前访问权;任意文件路径不能凭会话 ID 访问。授权撤销后旧消息引用也会被拒绝。适用于共享 Agent、组织共享库回答图片与消息产物,详见[文件访问](../03-features/21-file-access.md)。diff --git a/website-docs/06-development/02-database-schema.md b/website-docs/06-development/02-database-schema.mdindex 7d08185e3..9d0b37d91 100644--- a/website-docs/06-development/02-database-schema.md+++ b/website-docs/06-development/02-database-schema.md@@ -55,7 +55,7 @@ migrations/| 版本 | 变更 || --- | --- || 000080 | knowledge_bases.auto_tag_config |-| 000081 | messages.artifacts,持久化生成文件 |+| 000081 | messages.artifacts,持久化生成文件(000103 起改存 `message_artifacts` 表) || 000082 | tenant_sandbox_configs,多命名后端与配置变更租期 || 000083 | sessions.sandbox_config_id || 000084 | 个人记忆六张表、tenants.memory_config、messages.used_memories |@@ -67,6 +67,7 @@ migrations/| 000090 | tenant_skill_catalog;tenant_skills.catalog_id,回填已有安装 || 000091 | mcp_tool_approvals.enabled,默认 true || 000101 | knowledges.profile(文档画像),knowledge_bases.profile_config / generated_profile(AI 知识库描述) |+| 000103 | `message_artifacts` 表,从 `messages.artifacts` 回填;此后只读写新表。回填后旧列中有内容的行置为 NULL(列保留,兼容滚动升级中的旧实例);无法解析的 `file_size`/`created_at` 回退为 0 和消息创建时间,不中断迁移。down 迁移会把新表写回旧列 |SQLite 版本号独立演进,不能与 PostgreSQL 数字一一对应:@@ -79,6 +80,7 @@ SQLite 版本号独立演进,不能与 PostgreSQL 数字一一对应:| 000009 | 历史 Embed memory 标志列;当前渠道接口不暴露此字段 || 000010–000011 | 多标签关联、principal 模型 || 000012–000013 | 消息 usage、MCP 工具 enabled |+| 000023 | `message_artifacts` 表,回填并清空旧列(对应 PostgreSQL 000103) |基线 schema 与后续增量共同决定新建库和已有库的最终结果;不能只看新增迁移文件名判断 Lite 是否有某张表。@@ -120,7 +122,8 @@ SQLite 版本号独立演进,不能与 PostgreSQL 数字一一对应:| 表 | 用途 | 关键字段 || --- | --- | --- || `sessions` | 会话(对话上下文与检索参数快照) | `id`、`tenant_id`、`title`、`knowledge_base_id`、`agent_id`(FK→custom_agents)、`user_id`、`max_rounds`、`enable_rewrite`、`fallback_strategy`/`fallback_response`、`keyword_threshold`/`vector_threshold`、`embedding_top_k`/`rerank_top_k`/`rerank_threshold`、`rerank_model_id`/`summary_model_id`、`agent_config`/`context_config`(JSONB)、`sandbox_config_id` |-| `messages` | 消息 | `id`、`request_id`、`session_id`(FK)、`role`、`content`/`rendered_content`、`knowledge_references`(JSONB 引用)、`agent_steps`(JSONB,Agent 推理轨迹)、`mentioned_items`/`images`(JSONB)、`is_completed`/`is_fallback`、`channel`(web/IM 渠道)、`agent_id`+`agent_tenant_id`、`model_id`、`knowledge_id`、`agent_duration_ms`、`execution_context`、`artifacts`/`used_memories`/`usage`(JSONB) |+| `messages` | 消息 | `id`、`request_id`、`session_id`(FK)、`role`、`content`/`rendered_content`、`knowledge_references`(JSONB 引用)、`agent_steps`(JSONB,Agent 推理轨迹)、`mentioned_items`/`images`(JSONB)、`is_completed`/`is_fallback`、`channel`(web/IM 渠道)、`agent_id`+`agent_tenant_id`、`model_id`、`knowledge_id`、`agent_duration_ms`、`execution_context`、`used_memories`/`usage`(JSONB)。`artifacts` 列自 000103 起不再读写且已清空(仅为回滚与滚动升级保留),生成文件见 `message_artifacts` |+| `message_artifacts` | 技能生成的文件,一行一个(000103) | `session_id`、`message_id`、`position`(消息内序号,即下载接口的 index;与 `message_id` 唯一)、`url`(存储或 resource:// 引用,不返回客户端)、`file_name`/`file_type`/`file_size`、`content_hash`、`source_path`(同会话同路径视为同一文件的多个版本)、`mod_time`(RFC 3339 文本,保留纳秒精度供采集器比对)、`created_at`。无软删除,随消息软删除一并隐藏 || `message_suggestion_sets` | 建议问题集(000067) | `tenant_id`、`session_id`、`assistant_message_id`、`placement`(starter/follow_up)、`config_hash`+`locale`(缓存键,唯一)、`status`、`questions`(JSONB)、token/延迟统计、`lease_until` || `message_suggestion_events` | 建议问题曝光/点击事件 | `suggestion_set_id`(FK,CASCADE)、`question_id`、`event_type`、`actor_id` || `temporary_documents` | 会话内临时文档(000070) | `tenant_id`、`session_id`、`resource_ref`、`file_name`/`file_type`/`file_size`、`status`(uploaded/processing/ready/expired)、`content`、`chunks`(JSONB)、`expires_at` |