Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(artifacts): let users delete generated files (#3447)

lyingbug9e0c28fbc93f
diff --git a/frontend/src/api/artifacts.ts b/frontend/src/api/artifacts.ts
index c4e502717..2aa14cafe 100644
--- a/frontend/src/api/artifacts.ts
+++ b/frontend/src/api/artifacts.ts
@@ -1,4 +1,4 @@
-import { get } from '@/utils/request'
+import { del, get } from '@/utils/request'
/**
* One file in the artifact library: the latest version of a file a skill
@@ -47,3 +47,25 @@ export function listArtifactLibrary(params: ArtifactLibraryParams = {}) {
if (params.pageSize) query.page_size = params.pageSize
return get<ArtifactLibraryPage>('/api/v1/artifacts', { params: query })
}
+
+export interface ArtifactDeleteResult {
+ success: boolean
+ data: { file_name: string; deleted: number }
+}
+
+/**
+ * Deletes a file from the artifact library, along with every earlier version of
+ * it in the same session — a library row is the file, not one regeneration of
+ * it, so leaving the older versions behind would leave the row in place.
+ *
+ * The stored bytes are reclaimed unless something else still references them,
+ * so this is not reversible. Callers confirm with the user first.
+ */
+export function deleteArtifactLibraryItem(item: ArtifactLibraryItem) {
+ const query = new URLSearchParams({
+ session_id: item.session_id,
+ message_id: item.message_id,
+ index: String(item.index),
+ })
+ return del<ArtifactDeleteResult>(`/api/v1/artifacts?${query.toString()}`)
+}
diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts
index 31322c43c..e74c199fc 100644
--- a/frontend/src/api/chat/index.ts
+++ b/frontend/src/api/chat/index.ts
@@ -111,6 +111,12 @@ export interface ArtifactMeta {
source_path: string;
mod_time: string;
created_at: string;
+ /**
+ * Set when the user deleted the file. The entry stays in the list so the
+ * artifacts after it keep their index — which is their download address —
+ * so clients filter on this rather than on position.
+ */
+ deleted_at?: string;
}
// listMessageArtifacts returns the artifacts attached to a single assistant
@@ -142,3 +148,21 @@ export async function downloadArtifact(
`/api/v1/sessions/${session_id}/messages/${message_id}/artifacts/${index}/download`,
);
}
+
+// deleteMessageArtifact removes a generated file from the session. The stored
+// bytes are reclaimed, so this is not reversible; callers confirm first.
+//
+// The in-chat panel lists every regeneration of a file as its own row, so it
+// deletes exactly the row the user clicked. The artifact library folds them
+// into one entry and passes all_versions.
+export async function deleteMessageArtifact(
+ session_id: string,
+ message_id: string,
+ index: number,
+ allVersions = false,
+) {
+ const query = allVersions ? '?all_versions=true' : '';
+ return del(
+ `/api/v1/sessions/${session_id}/messages/${message_id}/artifacts/${index}${query}`,
+ );
+}
diff --git a/frontend/src/components/chat/SandboxSidePanel.vue b/frontend/src/components/chat/SandboxSidePanel.vue
index 1a168aed9..692c2076a 100644
--- a/frontend/src/components/chat/SandboxSidePanel.vue
+++ b/frontend/src/components/chat/SandboxSidePanel.vue
@@ -54,6 +54,7 @@
:items="artifacts"
:collecting="artifactsCollecting"
:active="panel?.activeTab.value === 'artifacts'"
+ @deleted="emit('artifactDeleted', $event)"
/>
<!-- 终端:首次激活时惰性挂载;切 tab 用 v-show 保留实例(不丢 PTY)。 -->
@@ -125,6 +126,10 @@ const props = withDefaults(
},
)
+// The artifact list is owned by the chat view (a computed over the loaded
+// history), so a delete inside the panel has to travel back up to it.
+const emit = defineEmits<{ (e: 'artifactDeleted', payload: { messageId: string; index: number }): void }>()
+
const { t } = useI18n()
const panel = useChatSandboxPanel()
const chatResources = useChatResourcesStore()
diff --git a/frontend/src/components/css/chat-markdown.less b/frontend/src/components/css/chat-markdown.less
index 2a26df943..82a7ff880 100644
--- a/frontend/src/components/css/chat-markdown.less
+++ b/frontend/src/components/css/chat-markdown.less
@@ -668,6 +668,7 @@
}
}
+ // 引用对不上任何产物:模型提到了一个并不存在的文件。
:deep(.artifact-ref-card--pending) {
cursor: default;
opacity: 0.7;
@@ -677,6 +678,27 @@
}
}
+ // 文件确实生成过,但用户删了它,字节已回收。整体置灰并给文件名加删除线,
+ // 好让它一眼区别于「从来没有过」的 --pending:这条回答当时确实产出了东西。
+ :deep(.artifact-ref-card--deleted) {
+ cursor: default;
+
+ &:hover {
+ background: transparent;
+ }
+
+ .artifact-ref-card__icon {
+ opacity: 0.45;
+ filter: grayscale(1);
+ }
+
+ .artifact-ref-card__name {
+ color: var(--td-text-color-placeholder);
+ text-decoration: line-through;
+ text-decoration-thickness: 1px;
+ }
+ }
+
:deep(.artifact-ref-card__icon) {
flex-shrink: 0;
width: 32px;
diff --git a/frontend/src/i18n/embed.ts b/frontend/src/i18n/embed.ts
index 2a96dba43..276e4222c 100644
--- a/frontend/src/i18n/embed.ts
+++ b/frontend/src/i18n/embed.ts
@@ -286,7 +286,8 @@ const messages = {
"download": "下载",
"downloadFailed": "下载失败,请稍后重试",
"inlinePreviewHint": "点击预览",
- "inlineMissing": "文件不可用"
+ "inlineMissing": "文件不可用",
+ "inlineDeleted": "文件已删除"
},
"updatePlan": "更新计划",
"webSearchFound": "找到 <strong>{count}</strong> 个网络搜索结果",
@@ -871,7 +872,8 @@ const messages = {
"download": "ダウンロード",
"downloadFailed": "ダウンロードに失敗しました。再試行してください。",
"inlinePreviewHint": "クリックしてプレビュー",
- "inlineMissing": "ファイルを利用できません"
+ "inlineMissing": "ファイルを利用できません",
+ "inlineDeleted": "ファイルは削除されました"
},
"updatePlan": "計画を更新",
"webSearchFound": "Web検索結果を<strong>{count}</strong>件見つけました",
@@ -1456,7 +1458,8 @@ const messages = {
"download": "Download",
"downloadFailed": "Download failed, please retry.",
"inlinePreviewHint": "Click to preview",
- "inlineMissing": "File unavailable"
+ "inlineMissing": "File unavailable",
+ "inlineDeleted": "File deleted"
},
"updatePlan": "Update Plan",
"webSearchFound": "Found <strong>{count}</strong> web search result(s)",
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 9f6d5c1fb..afa3cd03d 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -140,6 +140,12 @@ export default {
total: '{count} files',
versions: '{count} versions',
preview: 'Preview',
+ delete: 'Delete',
+ deleteTitle: 'Delete this file?',
+ deleteConfirm: '“{name}” and its stored contents will be permanently deleted. This cannot be undone.',
+ deleteConfirmVersions: 'All {count} versions of “{name}” and their stored contents will be permanently deleted. This cannot be undone.',
+ deleted: 'File deleted',
+ deleteFailed: 'Delete failed, please retry.',
download: 'Download',
downloadFailed: 'Download failed. Please try again later.',
openSession: 'Open conversation',
@@ -990,10 +996,16 @@ export default {
preview: 'Preview',
previewBack: 'Back to list',
collecting: 'Saving generated files…',
+ delete: 'Delete',
+ deleteTitle: 'Delete this file?',
+ deleteConfirm: '“{name}” and its stored contents will be permanently deleted. This cannot be undone.',
+ deleted: 'File deleted',
+ deleteFailed: 'Delete failed, please retry.',
download: 'Download',
downloadFailed: 'Download failed, please retry.',
inlinePreviewHint: 'Click to preview',
inlineMissing: 'File unavailable',
+ inlineDeleted: 'File deleted',
},
updatePlan: 'Update Plan',
webSearchFound: 'Found <strong>{count}</strong> web search result(s)',
diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts
index c5b3f6eea..932faed31 100644
--- a/frontend/src/i18n/locales/ja-JP.ts
+++ b/frontend/src/i18n/locales/ja-JP.ts
@@ -140,6 +140,12 @@ export default {
total: '{count} 件のファイル',
versions: '{count} バージョン',
preview: 'プレビュー',
+ delete: '削除',
+ deleteTitle: 'このファイルを削除しますか?',
+ deleteConfirm: '「{name}」と保存されている内容を完全に削除します。元に戻せません。',
+ deleteConfirmVersions: '「{name}」の全 {count} バージョンと保存されている内容を完全に削除します。元に戻せません。',
+ deleted: 'ファイルを削除しました',
+ deleteFailed: '削除に失敗しました。再試行してください。',
download: 'ダウンロード',
downloadFailed: 'ダウンロードに失敗しました。しばらくしてから再試行してください',
openSession: '会話を開く',
@@ -990,10 +996,16 @@ export default {
preview: 'プレビュー',
previewBack: '一覧に戻る',
collecting: '生成されたファイルを保存中…',
+ delete: '削除',
+ deleteTitle: 'このファイルを削除しますか?',
+ deleteConfirm: '「{name}」と保存されている内容を完全に削除します。元に戻せません。',
+ deleted: 'ファイルを削除しました',
+ deleteFailed: '削除に失敗しました。再試行してください。',
download: 'ダウンロード',
downloadFailed: 'ダウンロードに失敗しました。再試行してください。',
inlinePreviewHint: 'クリックしてプレビュー',
inlineMissing: 'ファイルを利用できません',
+ inlineDeleted: 'ファイルは削除されました',
},
updatePlan: 'プランを更新',
webSearchFound: 'Web検索結果を<strong>{count}</strong>件見つけました',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 165c1f5a0..7a05c85f3 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -6310,10 +6310,16 @@ export default {
preview: '미리보기',
previewBack: '목록으로',
collecting: '생성된 파일을 저장하는 중…',
+ delete: '삭제',
+ deleteTitle: '이 파일을 삭제할까요?',
+ deleteConfirm: '「{name}」과(와) 저장된 내용이 영구적으로 삭제되며 복구할 수 없습니다.',
+ deleted: '파일을 삭제했습니다',
+ deleteFailed: '삭제에 실패했습니다. 다시 시도해 주세요.',
download: '다운로드',
downloadFailed: '다운로드에 실패했습니다. 다시 시도해 주세요.',
inlinePreviewHint: '클릭하여 미리보기',
inlineMissing: '파일을 사용할 수 없습니다',
+ inlineDeleted: '삭제된 파일',
},
updatePlan: '계획 업데이트',
webSearchFound: '<strong>{count}</strong>개의 웹 검색 결과 발견',
@@ -7387,6 +7393,12 @@ export default {
total: '파일 {count}개',
versions: '버전 {count}개',
preview: '미리보기',
+ delete: '삭제',
+ deleteTitle: '이 파일을 삭제할까요?',
+ deleteConfirm: '「{name}」과(와) 저장된 내용이 영구적으로 삭제되며 복구할 수 없습니다.',
+ deleteConfirmVersions: '「{name}」의 {count}개 버전과 저장된 내용이 모두 영구적으로 삭제되며 복구할 수 없습니다.',
+ deleted: '파일을 삭제했습니다',
+ deleteFailed: '삭제에 실패했습니다. 다시 시도해 주세요.',
download: '다운로드',
downloadFailed: '다운로드에 실패했습니다. 잠시 후 다시 시도해 주세요',
openSession: '대화 열기',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index 55b9d1fe9..3321ee933 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -6310,10 +6310,16 @@ export default {
preview: 'Предпросмотр',
previewBack: 'Назад к списку',
collecting: 'Сохранение сгенерированных файлов…',
+ delete: 'Удалить',
+ deleteTitle: 'Удалить этот файл?',
+ deleteConfirm: '«{name}» и сохранённое содержимое будут удалены безвозвратно. Отменить нельзя.',
+ deleted: 'Файл удалён',
+ deleteFailed: 'Не удалось удалить, повторите попытку.',
download: 'Скачать',
downloadFailed: 'Не удалось скачать, повторите попытку.',
inlinePreviewHint: 'Нажмите для просмотра',
inlineMissing: 'Файл недоступен',
+ inlineDeleted: 'Файл удалён',
},
updatePlan: 'Обновить план',
webSearchFound: 'Найдено <strong>{count}</strong> результатов веб‑поиска',
@@ -7387,6 +7393,12 @@ export default {
total: 'Файлов: {count}',
versions: 'Версий: {count}',
preview: 'Предпросмотр',
+ delete: 'Удалить',
+ deleteTitle: 'Удалить этот файл?',
+ deleteConfirm: '«{name}» и сохранённое содержимое будут удалены безвозвратно. Отменить нельзя.',
+ deleteConfirmVersions: 'Все версии файла «{name}» ({count}) и их содержимое будут удалены безвозвратно. Отменить нельзя.',
+ deleted: 'Файл удалён',
+ deleteFailed: 'Не удалось удалить, повторите попытку.',
download: 'Скачать',
downloadFailed: 'Не удалось скачать файл. Повторите попытку позже',
openSession: 'Открыть диалог',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index 82c10bc6b..8d7eed33f 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -6312,10 +6312,16 @@ export default {
preview: '预览',
previewBack: '返回列表',
collecting: '正在保存生成的文件…',
+ delete: '删除',
+ deleteTitle: '删除这个文件?',
+ deleteConfirm: '将永久删除「{name}」,包括已保存的文件内容,且无法恢复。',
+ deleted: '文件已删除',
+ deleteFailed: '删除失败,请稍后重试',
download: '下载',
downloadFailed: '下载失败,请稍后重试',
inlinePreviewHint: '点击预览',
inlineMissing: '文件不可用',
+ inlineDeleted: '文件已删除',
},
updatePlan: '更新计划',
webSearchFound: '找到 <strong>{count}</strong> 个网络搜索结果',
@@ -7389,6 +7395,12 @@ export default {
total: '共 {count} 个文件',
versions: '{count} 个版本',
preview: '预览',
+ delete: '删除',
+ deleteTitle: '删除这个文件?',
+ deleteConfirm: '将永久删除「{name}」,包括已保存的文件内容,且无法恢复。',
+ deleteConfirmVersions: '将永久删除「{name}」的全部 {count} 个版本,包括已保存的文件内容,且无法恢复。',
+ deleted: '文件已删除',
+ deleteFailed: '删除失败,请稍后重试',
download: '下载',
downloadFailed: '下载失败,请稍后重试',
openSession: '打开所在会话',
diff --git a/frontend/src/utils/sandboxArtifactRefs.test.ts b/frontend/src/utils/sandboxArtifactRefs.test.ts
index e3ef5b71d..6d7c923a2 100644
--- a/frontend/src/utils/sandboxArtifactRefs.test.ts
+++ b/frontend/src/utils/sandboxArtifactRefs.test.ts
@@ -10,7 +10,7 @@ import {
type ArtifactRefMeta,
} from './sandboxArtifactRefs.ts'
-const labels = { previewHint: '点击预览', missingHint: '文件不可用' }
+const labels = { previewHint: '点击预览', missingHint: '文件不可用', deletedHint: '文件已删除' }
test('inline file cards reuse the drawer icon and keep filenames escaped', () => {
for (const name of ['report.pdf', 'table.xlsx', 'notes.docx', 'slides.pptx', 'chart.html', 'bad.<img src=x onerror=alert(1)>']) {
@@ -203,3 +203,46 @@ test('artifact names are HTML-escaped', () => {
assert.ok(!html?.includes('<img src=x'))
assert.ok(html?.includes('&lt;img'))
})
+
+test('a deleted artifact renders as a greyed, non-clickable card', () => {
+ const html = renderArtifactReference({
+ href: refFor(0),
+ alt: '市场画像评分',
+ artifacts: artifacts.map((a, i) =>
+ i === 0 ? { ...a, deleted_at: '2026-09-20T02:00:00Z' } : a,
+ ),
+ labels,
+ })
+ assert.ok(html?.includes('artifact-ref-card--deleted'))
+ assert.ok(html?.includes('文件已删除'))
+ assert.ok(html?.includes('市场画像评分_e7edba.html'), 'the name still says which file it was')
+ // Not clickable: the bytes are gone, so opening the preview would 404.
+ assert.ok(!html?.includes('data-artifact-index'))
+ assert.ok(!html?.includes('role="button"'))
+ // And distinguishable from a reference that never resolved at all.
+ assert.ok(!html?.includes('artifact-ref-card--pending'))
+})
+
+test('a deleted image artifact degrades to the card instead of a broken img', () => {
+ // renderImage would emit a placeholder that hydrateArtifactImages then fails
+ // to fill, leaving a permanently blank image in the answer.
+ const html = renderArtifactReference({
+ href: refFor(1),
+ alt: '走势',
+ artifacts: artifacts.map((a, i) =>
+ i === 1 ? { ...a, deleted_at: '2026-09-20T02:00:00Z' } : a,
+ ),
+ labels,
+ })
+ assert.ok(html?.includes('artifact-ref-card--deleted'))
+ assert.ok(!html?.includes('artifact-ref-image'))
+ assert.ok(!html?.includes('<img'))
+})
+
+test('a deleted artifact is not mistaken for a foreign handle', () => {
+ // Dropping tombstones before rendering would make the handle unresolvable,
+ // and an unresolved handle falls through to protected-image rendering — a
+ // broken image rather than an honest "deleted" card.
+ const live = artifacts.filter((_, i) => i !== 0)
+ assert.equal(renderArtifactReference({ href: refFor(0), artifacts: live, labels }), null)
+})
diff --git a/frontend/src/utils/sandboxArtifactRefs.ts b/frontend/src/utils/sandboxArtifactRefs.ts
index ee46e9222..d75ac376a 100644
--- a/frontend/src/utils/sandboxArtifactRefs.ts
+++ b/frontend/src/utils/sandboxArtifactRefs.ts
@@ -16,6 +16,10 @@
* 图片类产物内联显示(带鉴权拉取后换成 blob),其余类型(HTML 图表、CSV、
* 文档等)渲染成一张卡片,点击后交给右侧沙箱面板的产物页预览——正文里塞一个
* 1MB 的自包含 HTML iframe 既慢又不安全。
+ *
+ * 已被用户删除的产物在列表里是墓碑(带 deleted_at),渲染成一张置灰的不可点击
+ * 卡片。调用方**不要**把墓碑过滤掉再传进来:过滤了句柄就对不上本条回答的产物,
+ * 会被当成知识库图片走受保护图片渲染,最终显示成一张拉不出来的裂图。
*/
import { escapeHTML } from './security.ts';
@@ -33,6 +37,12 @@ export interface ArtifactRefMeta {
* 同义,取其一即可。
*/
url?: string;
+ /**
+ * 用户删除该文件的时间。墓碑条目**必须**留在传给渲染器的列表里:一是下标就是
+ * 下载地址,抽掉会让后面的文件整体错位;二是句柄只有对得上才知道它属于本条
+ * 回答,对不上会被当成知识库图片走受保护图片渲染,最后显示成一张裂图。
+ */
+ deleted_at?: string | null;
}
export interface ArtifactRefContext {
@@ -45,6 +55,8 @@ export interface ArtifactRefLabels {
previewHint: string;
/** 本轮已结束但引用对不上任何产物时的副标题,如「文件不可用」。 */
missingHint: string;
+ /** 文件已被用户删除时的副标题,如「文件已删除」。 */
+ deletedHint: string;
}
const RESOURCE_HANDLE_RE = /^resource:\/\/([A-Za-z0-9_-]{22})$/;
@@ -239,15 +251,29 @@ function blobCacheKey(ctx: ArtifactRefContext, index: number): string {
const STREAMING_PLACEHOLDER =
'<span class="streaming-image-loading"><span class="streaming-image-loading__skeleton"></span></span>';
-function renderCard(fileName: string, hint: string, index: number | null): string {
+/**
+ * 卡片的三种状态:
+ * - `ready` —— 正常,可点击打开预览;
+ * - `pending` —— 本轮已结束但引用对不上任何产物(模型引用了不存在的文件);
+ * - `deleted` —— 文件确实生成过,但已被用户删除,字节已回收。
+ * 后两种都不可点击,但要能区分开:一个是「从来没有过」,一个是「你自己删掉了」。
+ */
+type ArtifactCardVariant = 'ready' | 'pending' | 'deleted';
+
+function renderCard(
+ fileName: string,
+ hint: string,
+ index: number | null,
+ variant: ArtifactCardVariant,
+): string {
const safeName = escapeHTML(fileName);
const safeHint = escapeHTML(hint);
// 卡片必须是内联元素:marked 会把图片包在 <p> 里,块级元素会被 HTML 解析器
// 提到段落外面,破坏正文结构。
- const interactive = index === null
- ? ''
- : ` data-artifact-index="${index}" role="button" tabindex="0"`;
- const state = index === null ? ' artifact-ref-card--pending' : '';
+ const interactive = variant === 'ready' && index !== null
+ ? ` data-artifact-index="${index}" role="button" tabindex="0"`
+ : '';
+ const state = variant === 'ready' ? '' : ` artifact-ref-card--${variant}`;
return (
`<span class="artifact-ref-card${state}"${interactive} title="${safeName}">`
+ `<span class="artifact-ref-card__icon" aria-hidden="true">${renderArtifactFileIcon(fileName)}</span>`
@@ -305,13 +331,21 @@ export function renderArtifactReference(args: {
// 继续显示「生成中」。
const fallbackName = ref.name || (args.alt || '').trim();
if (!fallbackName) return '';
- return renderCard(fallbackName, args.labels.missingHint, null);
+ return renderCard(fallbackName, args.labels.missingHint, null, 'pending');
+ }
+
+ // 用户删过的文件字节已经回收,下载会 404。图片类产物同样降级成卡片:走
+ // renderImage 只会拉取失败,留下一张永远加载不出来的裂图。
+ if (artifact.deleted_at) {
+ const name = artifact.file_name || (args.alt || '').trim();
+ if (!name) return '';
+ return renderCard(name, args.labels.deletedHint, null, 'deleted');
}
if (rendersAsImage(artifact)) {
return renderImage(artifact, args.alt || '', args.context ?? null);
}
- return renderCard(artifact.file_name, args.labels.previewHint, artifact.index);
+ return renderCard(artifact.file_name, args.labels.previewHint, artifact.index, 'ready');
}
async function loadArtifactBlobURL(ctx: ArtifactRefContext, index: number): Promise<string | null> {
diff --git a/frontend/src/utils/sessionArtifacts.test.ts b/frontend/src/utils/sessionArtifacts.test.ts
index 03b6fd09a..8f7eaeeba 100644
--- a/frontend/src/utils/sessionArtifacts.test.ts
+++ b/frontend/src/utils/sessionArtifacts.test.ts
@@ -6,6 +6,7 @@ import {
collectSessionArtifacts,
formatArtifactDateTime,
formatArtifactSize,
+ markSessionArtifactDeleted,
} from './sessionArtifacts.ts'
test('collectSessionArtifacts keeps per-message download indexes', () => {
@@ -97,3 +98,45 @@ test('both answer renderers resolve the persisted artifact owner for inline prev
assert.match(source.slice(start, end), /persistedAssistantId\(props\.session\)/)
}
})
+
+test('collectSessionArtifacts hides deleted files but leaves the indexes after them alone', () => {
+ const items = collectSessionArtifacts([
+ {
+ role: 'assistant',
+ id: 'a1',
+ artifacts: [
+ { file_name: 'first.csv' },
+ { file_name: 'gone.pptx', deleted_at: '2026-09-20T02:00:00Z' },
+ { file_name: 'third.png' },
+ ],
+ },
+ ])
+ assert.deepEqual(
+ items.map((item) => ({ index: item.index, file_name: item.file_name })),
+ [
+ { index: 0, file_name: 'first.csv' },
+ // 2, not 1: the index is the download address, and the server keeps the
+ // deleted entry in place precisely so this one does not move.
+ { index: 2, file_name: 'third.png' },
+ ],
+ )
+})
+
+test('markSessionArtifactDeleted flags the row so the list drops it without a refetch', () => {
+ const deleted = { file_name: 'b.csv' } as { file_name: string; deleted_at?: string }
+ const messages = [
+ { role: 'user', id: 'u1', content: 'hi' },
+ { role: 'assistant', id: 'a1', artifacts: [{ file_name: 'a.csv' }, deleted] },
+ ]
+ assert.equal(markSessionArtifactDeleted(messages, 'a1', 1), true)
+ assert.ok(deleted.deleted_at)
+ assert.deepEqual(
+ collectSessionArtifacts(messages).map((item) => item.file_name),
+ ['a.csv'],
+ )
+
+ // Already flagged, unknown message, out-of-range index: all no-ops.
+ assert.equal(markSessionArtifactDeleted(messages, 'a1', 1), false)
+ assert.equal(markSessionArtifactDeleted(messages, 'nope', 0), false)
+ assert.equal(markSessionArtifactDeleted(messages, 'a1', 9), false)
+})
diff --git a/frontend/src/utils/sessionArtifacts.ts b/frontend/src/utils/sessionArtifacts.ts
index f7423cb90..2542b420e 100644
--- a/frontend/src/utils/sessionArtifacts.ts
+++ b/frontend/src/utils/sessionArtifacts.ts
@@ -19,6 +19,10 @@ function readMessageId(message: Record<string, unknown>): string {
* Flatten every assistant message's artifacts in list order. Download still
* uses the per-message index (not a session-wide offset), so each row keeps
* the owning message id.
+ *
+ * Deleted artifacts are dropped but still consume their index: the server keeps
+ * them in the list precisely so the files after them keep their download
+ * address, and renumbering here would undo that.
*/
export function collectSessionArtifacts(messages: unknown): SessionArtifactItem[] {
if (!Array.isArray(messages)) return []
@@ -33,6 +37,7 @@ export function collectSessionArtifacts(messages: unknown): SessionArtifactItem[
for (let i = 0; i < list.length; i++) {
const art = asRecord(list[i])
if (!art) continue
+ if (art.deleted_at) continue
const index = Number.isInteger(art.index) ? (art.index as number) : i
items.push({
...(art as unknown as ArtifactMeta),
@@ -44,6 +49,32 @@ export function collectSessionArtifacts(messages: unknown): SessionArtifactItem[
return items
}
+/**
+ * Marks an artifact deleted in the loaded history so the panel drops it without
+ * a refetch. Returns whether anything changed.
+ *
+ * The entry is flagged rather than spliced out, for the same reason the server
+ * keeps a tombstone: its position is the download address of the file, and
+ * removing it would shift every later artifact of that message.
+ */
+export function markSessionArtifactDeleted(
+ messages: unknown,
+ messageId: string,
+ index: number,
+): boolean {
+ if (!Array.isArray(messages) || !messageId) return false
+ for (const raw of messages) {
+ const message = asRecord(raw)
+ if (!message || readMessageId(message) !== messageId) continue
+ const list = Array.isArray(message.artifacts) ? message.artifacts : []
+ const art = asRecord(list[index])
+ if (!art || art.deleted_at) continue
+ art.deleted_at = new Date().toISOString()
+ return true
+ }
+ return false
+}
+
export function formatArtifactSize(size: number | undefined | null): string {
if (!size || size < 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB']
diff --git a/frontend/src/views/artifacts/ArtifactLibrary.vue b/frontend/src/views/artifacts/ArtifactLibrary.vue
index 066011460..fe1c9e944 100644
--- a/frontend/src/views/artifacts/ArtifactLibrary.vue
+++ b/frontend/src/views/artifacts/ArtifactLibrary.vue
@@ -115,6 +115,18 @@
>
<template #icon><t-icon name="download" size="16px" /></template>
</t-button>
+ <t-button
+ class="row-action row-action--danger"
+ variant="text"
+ shape="square"
+ size="small"
+ :title="$t('artifactLibrary.delete')"
+ :aria-label="$t('artifactLibrary.delete')"
+ :loading="isDeleting(item)"
+ @click.stop="handleDelete(item)"
+ >
+ <template #icon><t-icon name="delete" size="16px" /></template>
+ </t-button>
</li>
</ul>
</section>
@@ -162,6 +174,18 @@
>
<template #icon><t-icon name="download" size="16px" /></template>
</t-button>
+ <t-button
+ class="row-action row-action--danger"
+ variant="text"
+ shape="square"
+ size="small"
+ :title="$t('artifactLibrary.delete')"
+ :aria-label="$t('artifactLibrary.delete')"
+ :loading="isDeleting(previewItem)"
+ @click="handleDelete(previewItem)"
+ >
+ <template #icon><t-icon name="delete" size="16px" /></template>
+ </t-button>
<t-button
class="row-action"
variant="text"
@@ -198,7 +222,7 @@ 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 { deleteArtifactLibraryItem, listArtifactLibrary, type ArtifactLibraryItem } from '@/api/artifacts'
import {
ARTIFACT_CATEGORIES,
artifactCategoryExtensions,
@@ -208,6 +232,7 @@ import {
} from '@/utils/artifactLibrary'
import { formatArtifactDateTime, formatArtifactSize } from '@/utils/sessionArtifacts'
import { resolveFilePreviewExt } from '@/utils/filePreview'
+import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import EmptyState from '@/components/EmptyState.vue'
import ResourceIcon from '@/components/icons/ResourceIcon.vue'
import DocumentPreview from '@/components/document-preview.vue'
@@ -219,6 +244,7 @@ const SEARCH_DEBOUNCE_MS = 300
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
+const confirmDelete = useConfirmDelete()
const category = ref<ArtifactCategory>(parseArtifactCategory(route.query.type))
const keyword = ref(typeof route.query.q === 'string' ? route.query.q : '')
@@ -228,6 +254,7 @@ const page = ref(0)
const loading = ref(false)
const loadError = ref(false)
const downloading = reactive<Record<string, boolean>>({})
+const deleting = reactive<Record<string, boolean>>({})
const previewItem = ref<ArtifactLibraryItem | null>(null)
const previewVisible = ref(false)
const previewActions = ref<HTMLElement | null>(null)
@@ -259,7 +286,15 @@ async function fetchPage(nextPage: number) {
})
if (mine !== ticket) return
const rows = Array.isArray(res?.data) ? res.data : []
- items.value = nextPage === 1 ? rows : [...items.value, ...rows]
+ // Deleting a row shifts every later row one page-offset earlier, so an
+ // appended page can overlap what is already shown. Drop the repeats rather
+ // than rendering an item twice under the same key.
+ if (nextPage === 1) {
+ items.value = rows
+ } else {
+ const shown = new Set(items.value.map(itemKey))
+ items.value = [...items.value, ...rows.filter((row) => !shown.has(itemKey(row)))]
+ }
total.value = typeof res?.total === 'number' ? res.total : items.value.length
page.value = nextPage
} catch (err) {
@@ -281,7 +316,9 @@ function reload() {
function loadMore() {
if (loading.value || !hasMore.value) return
- void fetchPage(page.value + 1)
+ // Page from how many rows are actually shown, not from the last page number:
+ // after a delete those differ, and paging by number would skip a row.
+ void fetchPage(Math.floor(items.value.length / PAGE_SIZE) + 1)
}
function syncQuery() {
@@ -328,16 +365,16 @@ function openSession(item: ArtifactLibraryItem) {
void router.push(`/platform/chat/${item.session_id}`)
}
-function downloadKey(item: ArtifactLibraryItem) {
+function itemKey(item: ArtifactLibraryItem) {
return `${item.message_id}:${item.index}`
}
function isDownloading(item: ArtifactLibraryItem) {
- return !!downloading[downloadKey(item)]
+ return !!downloading[itemKey(item)]
}
async function handleDownload(item: ArtifactLibraryItem) {
- const key = downloadKey(item)
+ const key = itemKey(item)
if (downloading[key]) return
downloading[key] = true
try {
@@ -358,6 +395,48 @@ async function handleDownload(item: ArtifactLibraryItem) {
}
}
+function isDeleting(item: ArtifactLibraryItem) {
+ return !!deleting[itemKey(item)]
+}
+
+// A library row is the file, not one regeneration of it, so the confirmation
+// says how many versions go with it. The bytes are reclaimed server side, which
+// is why this asks at all.
+function handleDelete(item: ArtifactLibraryItem) {
+ if (isDeleting(item)) return
+ confirmDelete({
+ title: t('artifactLibrary.deleteTitle'),
+ body:
+ item.version_count > 1
+ ? t('artifactLibrary.deleteConfirmVersions', { name: item.file_name, count: item.version_count })
+ : t('artifactLibrary.deleteConfirm', { name: item.file_name }),
+ onConfirm: () => performDelete(item),
+ })
+}
+
+async function performDelete(item: ArtifactLibraryItem) {
+ const key = itemKey(item)
+ if (deleting[key]) return
+ deleting[key] = true
+ try {
+ await deleteArtifactLibraryItem(item)
+ // Splice the row out instead of reloading: this is an infinite list, and a
+ // reload would throw away everything the user has scrolled past.
+ const at = items.value.findIndex((row) => itemKey(row) === key)
+ if (at >= 0) {
+ items.value.splice(at, 1)
+ total.value = Math.max(0, total.value - 1)
+ }
+ if (previewItem.value && itemKey(previewItem.value) === key) previewVisible.value = false
+ MessagePlugin.success(t('artifactLibrary.deleted'))
+ } catch (err) {
+ console.error('[ArtifactLibrary] delete failed:', err)
+ MessagePlugin.error(t('artifactLibrary.deleteFailed'))
+ } finally {
+ deleting[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
@@ -628,6 +707,11 @@ onBeforeUnmount(() => {
:deep(.t-button__icon) {
margin: 0;
}
+
+ &--danger:not(.t-is-disabled):not(.t-is-loading):hover {
+ background: var(--td-error-color-1);
+ color: var(--td-error-color);
+ }
}
.list-footer {
diff --git a/frontend/src/views/chat/components/AgentStreamDisplay.vue b/frontend/src/views/chat/components/AgentStreamDisplay.vue
index 8fac74f00..8f2464221 100644
--- a/frontend/src/views/chat/components/AgentStreamDisplay.vue
+++ b/frontend/src/views/chat/components/AgentStreamDisplay.vue
@@ -601,7 +601,7 @@
v-model:visible="showArtifactDrawer"
:session-id="sessionIdForArtifacts"
:message-id="messageIdForArtifacts"
- :artifacts="artifactList"
+ :artifacts="liveArtifacts"
:preview-index="artifactPreviewIndex"
/>
</template>
@@ -1055,8 +1055,13 @@ const artifactList = computed(() => {
const list = ((props.session?.artifacts as any[]) || []);
return list.map((a, i) => ({ index: i, ...a }));
});
-const hasArtifacts = computed(() => artifactList.value.length > 0);
-const artifactCount = computed(() => artifactList.value.length);
+// Deleted files stay in artifactList on purpose: the inline renderer needs the
+// tombstone to tell "you deleted this" apart from "this handle belongs to some
+// other message", and its position is still the download address of the files
+// after it. Everything that counts or lists files uses the live view.
+const liveArtifacts = computed(() => artifactList.value.filter((a) => !a.deleted_at));
+const hasArtifacts = computed(() => liveArtifacts.value.length > 0);
+const artifactCount = computed(() => liveArtifacts.value.length);
const { artifactArrived, onArtifactArriveEnd } = useArtifactArriveMotion(artifactCount);
const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.session as any));
const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value);
@@ -1094,6 +1099,7 @@ const artifactRefContext = computed(() => {
const artifactRefLabels = computed(() => ({
previewHint: t('agent.artifactDrawer.inlinePreviewHint'),
missingHint: t('agent.artifactDrawer.inlineMissing'),
+ deletedHint: t('agent.artifactDrawer.inlineDeleted'),
}));
const {
diff --git a/frontend/src/views/chat/components/ChatArtifactsPanel.vue b/frontend/src/views/chat/components/ChatArtifactsPanel.vue
index cd60e8da5..edf7e0399 100644
--- a/frontend/src/views/chat/components/ChatArtifactsPanel.vue
+++ b/frontend/src/views/chat/components/ChatArtifactsPanel.vue
@@ -30,6 +30,20 @@
<t-icon name="download" size="16px" />
</template>
</t-button>
+ <t-button
+ class="artifact-download artifact-delete"
+ variant="text"
+ shape="square"
+ size="small"
+ :title="$t('agent.artifactDrawer.delete')"
+ :aria-label="$t('agent.artifactDrawer.delete')"
+ :loading="isDeleting(previewItem)"
+ @click="handleDelete(previewItem)"
+ >
+ <template #icon>
+ <t-icon name="delete" size="16px" />
+ </template>
+ </t-button>
<div ref="previewActions" class="artifact-preview-actions" />
</div>
@@ -123,6 +137,20 @@
<t-icon name="download" size="16px" />
</template>
</t-button>
+ <t-button
+ class="artifact-download artifact-delete"
+ variant="text"
+ shape="square"
+ size="small"
+ :title="$t('agent.artifactDrawer.delete')"
+ :aria-label="$t('agent.artifactDrawer.delete')"
+ :loading="isDeleting(item)"
+ @click.stop="handleDelete(item)"
+ >
+ <template #icon>
+ <t-icon name="delete" size="16px" />
+ </template>
+ </t-button>
</li>
</ul>
</template>
@@ -133,7 +161,7 @@
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
-import { downloadArtifact } from '@/api/chat'
+import { deleteMessageArtifact, downloadArtifact } from '@/api/chat'
import { resolveFilePreviewExt } from '@/utils/filePreview'
import {
formatArtifactDateTime,
@@ -141,6 +169,7 @@ import {
type SessionArtifactItem,
} from '@/utils/sessionArtifacts'
import { useChatSandboxPanel, type ArtifactPanelFocusState } from '@/composables/useChatSandboxPanel'
+import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import DocumentPreview from '@/components/document-preview.vue'
import ArtifactFileIcon from './ArtifactFileIcon.vue'
@@ -157,12 +186,18 @@ const props = withDefaults(
},
)
+// The list is a computed over the loaded history, so the panel reports the
+// delete upward instead of mutating its own prop.
+const emit = defineEmits<{ (e: 'deleted', payload: { messageId: string; index: number }): void }>()
+
const { t } = useI18n()
const panel = useChatSandboxPanel()
+const confirmDelete = useConfirmDelete()
const previewActions = ref<HTMLElement | null>(null)
const listRef = ref<HTMLElement | null>(null)
const previewItem = ref<SessionArtifactItem | null>(null)
const downloading = reactive<Record<string, boolean>>({})
+const deleting = reactive<Record<string, boolean>>({})
const focusedMessageId = ref<string | null>(null)
const scope = ref<'current' | 'all'>('all')
const searchQuery = ref('')
@@ -187,6 +222,42 @@ function isDownloading(item: SessionArtifactItem): boolean {
return !!downloading[downloadKey(item)]
}
+function isDeleting(item: SessionArtifactItem): boolean {
+ return !!deleting[downloadKey(item)]
+}
+
+// Each row here is one regeneration of a file, so the delete takes just that
+// version. The artifact library, which folds versions into one entry, is where
+// deleting the whole file lives.
+function handleDelete(item: SessionArtifactItem) {
+ if (isDeleting(item)) return
+ confirmDelete({
+ title: t('agent.artifactDrawer.deleteTitle'),
+ body: t('agent.artifactDrawer.deleteConfirm', { name: item.file_name }),
+ onConfirm: () => performDelete(item),
+ })
+}
+
+async function performDelete(item: SessionArtifactItem) {
+ if (!props.sessionId || !item.messageId) {
+ MessagePlugin.error(t('agent.artifactDrawer.deleteFailed'))
+ return
+ }
+ const key = downloadKey(item)
+ deleting[key] = true
+ try {
+ await deleteMessageArtifact(props.sessionId, item.messageId, item.index)
+ if (previewItem.value && downloadKey(previewItem.value) === key) previewItem.value = null
+ emit('deleted', { messageId: item.messageId, index: item.index })
+ MessagePlugin.success(t('agent.artifactDrawer.deleted'))
+ } catch (err) {
+ console.error('[ChatArtifactsPanel] delete failed:', err)
+ MessagePlugin.error(t('agent.artifactDrawer.deleteFailed'))
+ } finally {
+ deleting[key] = false
+ }
+}
+
function findItem(messageId: string, previewIndex?: number | null): SessionArtifactItem | undefined {
if (previewIndex != null && Number.isInteger(previewIndex)) {
return props.items.find((item) => item.messageId === messageId && item.index === previewIndex)
@@ -518,6 +589,11 @@ async function handleDownload(item: SessionArtifactItem) {
outline-offset: 2px;
}
+ &.artifact-delete:not(.t-is-disabled):not(.t-is-loading):hover {
+ background: var(--td-error-color-1);
+ color: var(--td-error-color);
+ }
+
:deep(.t-button__icon) {
margin: 0;
}
diff --git a/frontend/src/views/chat/components/botmsg.vue b/frontend/src/views/chat/components/botmsg.vue
index 42ddb0a26..d92a941ae 100644
--- a/frontend/src/views/chat/components/botmsg.vue
+++ b/frontend/src/views/chat/components/botmsg.vue
@@ -107,7 +107,7 @@
v-model:visible="showArtifactDrawer"
:session-id="sessionId"
:message-id="messageIdForArtifacts"
- :artifacts="artifactList"
+ :artifacts="liveArtifacts"
:preview-index="artifactPreviewIndex"
/>
</div>
@@ -250,8 +250,13 @@ const artifactList = computed(() => {
// omit it. Normalising here keeps ChatArtifactsDrawer index-agnostic.
return list.map((a, i) => ({ index: i, ...a }));
});
-const hasArtifacts = computed(() => artifactList.value.length > 0);
-const artifactCount = computed(() => artifactList.value.length);
+// Deleted files stay in artifactList on purpose: the inline renderer needs the
+// tombstone to tell "you deleted this" apart from "this handle belongs to some
+// other message", and its position is still the download address of the files
+// after it. Everything that counts or lists files uses the live view.
+const liveArtifacts = computed(() => artifactList.value.filter((a) => !a.deleted_at));
+const hasArtifacts = computed(() => liveArtifacts.value.length > 0);
+const artifactCount = computed(() => liveArtifacts.value.length);
const { artifactArrived, onArtifactArriveEnd } = useArtifactArriveMotion(artifactCount);
const artifactsCollecting = computed(() => isCollectingSkillArtifacts(props.session));
const artifactButtonCollecting = computed(() => artifactsCollecting.value && !hasArtifacts.value);
@@ -289,6 +294,7 @@ const artifactRefContext = computed(() => {
const artifactRefLabels = computed(() => ({
previewHint: t('agent.artifactDrawer.inlinePreviewHint'),
missingHint: t('agent.artifactDrawer.inlineMissing'),
+ deletedHint: t('agent.artifactDrawer.inlineDeleted'),
}));
const preview = (url) => {
diff --git a/frontend/src/views/chat/index.vue b/frontend/src/views/chat/index.vue
index 7944c9ce2..b1fb0bf7b 100644
--- a/frontend/src/views/chat/index.vue
+++ b/frontend/src/views/chat/index.vue
@@ -182,7 +182,8 @@
:agent-id="useSettingsStoreInstance.selectedAgentId"
:agent-source-tenant-id="useSettingsStoreInstance.selectedAgentSourceTenantId"
:shifted="referencesDrawerVisible"
- :artifacts="sessionArtifacts" :artifacts-collecting="sessionArtifactsCollecting" />
+ :artifacts="sessionArtifacts" :artifacts-collecting="sessionArtifactsCollecting"
+ @artifact-deleted="handleArtifactDeleted" />
</template>
<script setup>
import { makeSteerClientId } from '@/utils/steerId';
@@ -233,7 +234,7 @@ import { useSessionActivityStore } from '@/stores/sessionActivity';
import { provideChatSandboxPanel } from '@/composables/useChatSandboxPanel';
import SandboxSidePanel from '@/components/chat/SandboxSidePanel.vue';
import BrowserTaskPreview from './components/BrowserTaskPreview.vue';
-import { collectSessionArtifacts } from '@/utils/sessionArtifacts';
+import { collectSessionArtifacts, markSessionArtifactDeleted } from '@/utils/sessionArtifacts';
import { isCollectingSkillArtifacts } from '@/utils/skillArtifacts';
const referencesDrawer = provideChatReferencesDrawer();
provideChatAttachmentPreviewDrawer();
@@ -415,6 +416,11 @@ async function handleFork(messageId) {
}
const sessionArtifacts = computed(() => collectSessionArtifacts(messagesList));
+// The panel already deleted the file server side; flag it in the loaded
+// history so the computed drops it without reloading the conversation.
+function handleArtifactDeleted({ messageId, index }) {
+ markSessionArtifactDeleted(messagesList, messageId, index);
+}
const sessionArtifactsCollecting = computed(() =>
messagesList.some((message) => isCollectingSkillArtifacts(message)),
);
diff --git a/internal/application/access/files.go b/internal/application/access/files.go
index f18e6bcb8..e179a3ee5 100644
--- a/internal/application/access/files.go
+++ b/internal/application/access/files.go
@@ -95,19 +95,55 @@ func ResolveKBFile(
return file, nil
}
+// artifactRefState says whether a reference names one of this message's
+// artifacts, and if so whether the user has deleted it.
+type artifactRefState int
+
+const (
+ artifactRefNone artifactRefState = iota
+ artifactRefLive
+ artifactRefDeleted
+)
+
+// artifactReferenceState resolves a reference against the message's artifacts.
+// A live row anywhere in the list wins over a tombstone: the same file can be
+// attached twice at different positions, and one of them still being there
+// means the message really does still offer it.
+func artifactReferenceState(message *types.Message, reference string) artifactRefState {
+ state := artifactRefNone
+ for _, artifact := range message.Artifacts {
+ if artifact.URL != reference {
+ continue
+ }
+ if !artifact.Deleted() {
+ return artifactRefLive
+ }
+ state = artifactRefDeleted
+ }
+ return state
+}
+
// MessageReferencesFile examines only persisted rendering/output fields. Tool
// arguments and request metadata are not evidence of a returned file.
func MessageReferencesFile(message *types.Message, reference string) bool {
if message == nil {
return false
}
- if types.ContainsStorageReference(message.Content, reference) {
+ // Artifacts are checked before the answer text, and a deleted one is a hard
+ // no. Deleting a generated file does not rewrite the answer that produced
+ // it, so its `resource://` handle is still sitting in message.Content; if
+ // the text were consulted first, the message-scoped file proxy would keep
+ // serving a file the user deleted — including to a shared-agent visitor,
+ // and including the case where the bytes survived because a knowledge entry
+ // still holds them. Those other owners have their own access paths.
+ switch artifactReferenceState(message, reference) {
+ case artifactRefDeleted:
+ return false
+ case artifactRefLive:
return true
}
- for _, artifact := range message.Artifacts {
- if artifact.URL == reference {
- return true
- }
+ if types.ContainsStorageReference(message.Content, reference) {
+ return true
}
for _, value := range []interface{}{message.KnowledgeReferences, message.Images} {
data, _ := json.Marshal(value)
@@ -240,6 +276,11 @@ func ResolveMessageArtifact(ctx context.Context, message *types.Message, index i
return FileAccess{}, ErrNotFound
}
artifact := message.Artifacts[index]
+ // Tombstones keep their slot so the indices of later artifacts stay put;
+ // they are not downloadable through any path, shared or owned.
+ if artifact.Deleted() {
+ return FileAccess{}, ErrNotFound
+ }
file, resource, err := resolveFile(ctx, catalog, artifact.URL)
if err != nil {
return FileAccess{}, err
diff --git a/internal/application/access/files_test.go b/internal/application/access/files_test.go
index e6693527f..a3147989e 100644
--- a/internal/application/access/files_test.go
+++ b/internal/application/access/files_test.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"testing"
+ "time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/stretchr/testify/require"
@@ -160,3 +161,66 @@ func (artifactFileCatalog) GetMessageFileBindings(
) (*types.MessageFileBindings, error) {
return &types.MessageFileBindings{MessageArtifact: messageID == "message"}, nil
}
+
+// Deleting a generated file does not rewrite the answer that produced it, so
+// its handle stays in message.Content. The message-scoped file proxy must not
+// treat that leftover text as permission to keep serving the file — including
+// when the bytes survived because a knowledge entry still holds them, and
+// including for a shared-agent visitor who never had delete rights.
+func TestDeletedArtifactIsNotServedFromTheAnswerText(t *testing.T) {
+ const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
+ deletedAt := time.Now()
+ messages := &fileMessages{message: &types.Message{
+ ID: "message", AgentID: "agent", AgentTenantID: 2, Role: "assistant",
+ Content: "![report](" + ref + ")",
+ Artifacts: types.MessageArtifacts{{URL: ref, FileName: "report.pdf"}},
+ }}
+ agents := &agentLookup{agent: &types.CustomAgent{ID: "agent", TenantID: 2}}
+ catalog := artifactFileCatalog{
+ fileCatalog{&types.StoredResource{TenantID: 2, PhysicalPath: "local://2/exports/report.pdf"}},
+ }
+ ctx := types.WithExecutionTenant(callerContext(), 2)
+
+ _, err := ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
+ require.NoError(t, err, "a live artifact is served as before")
+
+ messages.message.Artifacts[0].DeletedAt = &deletedAt
+ _, err = ResolveMessageFile(ctx, "session", "message", ref, messages, agents, catalog, MessageKBShareAuthorizer{})
+ require.ErrorIs(t, err, ErrForbidden, "the handle left in the answer text must not re-authorize a deleted file")
+
+ // The index-addressed artifact download agrees.
+ _, err = ResolveMessageArtifact(ctx, messages.message, 0, agents, catalog, MessageKBShareAuthorizer{})
+ require.ErrorIs(t, err, ErrNotFound)
+}
+
+// The same file can be attached twice at different positions. One of them
+// still being live means the message really does still offer it.
+func TestOneLiveCopyKeepsTheFileServable(t *testing.T) {
+ const ref = "resource://AbCdEfGhIjKlMnOpQrStUv"
+ deletedAt := time.Now()
+ message := &types.Message{
+ ID: "message", AgentTenantID: 1, Role: "assistant",
+ Content: "![report](" + ref + ")",
+ Artifacts: types.MessageArtifacts{
+ {URL: ref, FileName: "report.pdf", DeletedAt: &deletedAt},
+ {URL: ref, FileName: "report.pdf"},
+ },
+ }
+ require.True(t, MessageReferencesFile(message, ref))
+
+ message.Artifacts[1].DeletedAt = &deletedAt
+ require.False(t, MessageReferencesFile(message, ref), "with every copy deleted the message no longer offers it")
+}
+
+// A reference the message never produced as an artifact keeps its old path:
+// knowledge-base images and user attachments are authorized by the text.
+func TestNonArtifactReferencesStillAuthorizeFromContent(t *testing.T) {
+ const kbImage = "resource://ZzZzZzZzZzZzZzZzZzZzZz"
+ deletedAt := time.Now()
+ message := &types.Message{
+ ID: "message", AgentTenantID: 1, Role: "assistant",
+ Content: "![kb](" + kbImage + ")",
+ Artifacts: types.MessageArtifacts{{URL: "resource://AbCdEfGhIjKlMnOpQrStUv", DeletedAt: &deletedAt}},
+ }
+ require.True(t, MessageReferencesFile(message, kbImage))
+}
diff --git a/internal/application/repository/message_artifact.go b/internal/application/repository/message_artifact.go
index ac71c7d9a..bce79c26b 100644
--- a/internal/application/repository/message_artifact.go
+++ b/internal/application/repository/message_artifact.go
@@ -2,6 +2,7 @@ package repository
import (
"context"
+ "errors"
"strings"
"time"
@@ -22,10 +23,22 @@ 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.
+//
+// A delete that already happened is re-applied on top of the incoming list, by
+// position. The caller usually carries the tombstones itself (they round-trip
+// through MessageArtifact.DeletedAt), but it may be holding a slice it read
+// before the delete — this is a full replace, so that snapshot would resurrect
+// the row while its bytes are already being reclaimed, leaving a live-looking
+// entry whose download 404s. Deletion is the one property of a row that a stale
+// writer must not be able to undo.
func writeMessageArtifacts(tx *gorm.DB, message *types.Message) error {
if message == nil || message.Artifacts == nil || message.ID == "" {
return nil
}
+ deleted, err := deletedArtifactPositions(tx, message.ID)
+ if err != nil {
+ return err
+ }
if err := tx.Where("message_id = ?", message.ID).
Delete(&types.MessageArtifactRecord{}).Error; err != nil {
return err
@@ -34,9 +47,33 @@ func writeMessageArtifacts(tx *gorm.DB, message *types.Message) error {
if len(rows) == 0 {
return nil
}
+ for i := range rows {
+ if at, ok := deleted[rows[i].Position]; ok && rows[i].DeletedAt == nil {
+ rows[i].DeletedAt = at
+ }
+ }
return tx.CreateInBatches(rows, 100).Error
}
+// deletedArtifactPositions returns the stored deletion times of a message's
+// tombstoned artifacts, keyed by position.
+func deletedArtifactPositions(tx *gorm.DB, messageID string) (map[int]*time.Time, error) {
+ var rows []types.MessageArtifactRecord
+ if err := tx.Select("position", "deleted_at").
+ Where("message_id = ? AND deleted_at IS NOT NULL", messageID).
+ Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ if len(rows) == 0 {
+ return nil, nil
+ }
+ out := make(map[int]*time.Time, len(rows))
+ for _, row := range rows {
+ out[row.Position] = row.DeletedAt
+ }
+ return out, nil
+}
+
// insertMessageArtifacts writes the artifacts of freshly created messages.
// Unlike writeMessageArtifacts it skips the delete, since new messages have
// no rows yet.
@@ -57,6 +94,11 @@ func insertMessageArtifacts(tx *gorm.DB, messages []*types.Message) 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.
+//
+// Tombstones (deleted_at set) are deliberately included: position is the index
+// the download endpoint addresses a file by, so skipping a deleted row here
+// would renumber every later file in the message. Callers that render a list
+// filter with MessageArtifacts.Live.
func loadArtifactsByMessage(
ctx context.Context, db *gorm.DB, messageIDs []string,
) (map[string]types.MessageArtifacts, error) {
@@ -116,6 +158,12 @@ func attachArtifactsWithSession(ctx context.Context, db *gorm.DB, results []*typ
// GetSessionArtifacts returns every skill-produced MessageArtifact recorded
// against a live message of the session, in message then position order.
+//
+// User-deleted artifacts are included as tombstones. ArtifactCollector builds
+// its de-duplication set from this call, and a tombstone is exactly what stops
+// it re-attaching a file the user deleted while the sandbox copy — same path,
+// same mtime — is still sitting there. Display paths filter with
+// MessageArtifacts.Live.
func (r *messageRepository) GetSessionArtifacts(
ctx context.Context, sessionID string,
) (types.MessageArtifacts, error) {
@@ -143,6 +191,11 @@ func (r *messageRepository) GetSessionArtifacts(
// 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.
+//
+// Tombstones are left alone too. A tombstone records what was deleted and when;
+// its (path, mtime) pair is the key that keeps the collector from re-attaching
+// the sandbox copy, so moving that mtime forward would quietly re-open the
+// door it is there to hold shut.
func (r *messageRepository) RecordRestoredArtifactMtime(
ctx context.Context, sessionID, sourcePath string, mod time.Time, hash string,
) error {
@@ -151,7 +204,8 @@ func (r *messageRepository) RecordRestoredArtifactMtime(
}
var rows []types.MessageArtifactRecord
if err := r.db.WithContext(ctx).
- Where("session_id = ? AND source_path = ? AND content_hash = ?", sessionID, sourcePath, hash).
+ Where("session_id = ? AND source_path = ? AND content_hash = ? AND deleted_at IS NULL",
+ sessionID, sourcePath, hash).
Find(&rows).Error; err != nil {
return err
}
@@ -172,6 +226,10 @@ func (r *messageRepository) RecordRestoredArtifactMtime(
// ListArtifactLibrary returns the latest version of every artifact in the
// sessions the caller can see, newest first.
//
+// User-deleted artifacts are excluded, versions included: deleting the newest
+// version of a file surfaces the one before it, which is why the delete path
+// tombstones every version of a library row at once.
+//
// 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,
@@ -188,7 +246,7 @@ func (r *messageRepository) ListArtifactLibrary(
where []string
args []any
)
- where = append(where, "s.tenant_id = ?", "s.deleted_at IS NULL")
+ where = append(where, "s.tenant_id = ?", "s.deleted_at IS NULL", "ma.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 = '')")
@@ -248,3 +306,126 @@ func (r *messageRepository) ListArtifactLibrary(
}
return items, total, nil
}
+
+// FindSessionArtifact returns one live artifact row of the session addressed by
+// (message, position) — the same coordinates the download endpoint uses.
+// A tombstone is reported as not found, so deleting twice is a 404 rather than
+// a second blob reclaim.
+func (r *messageRepository) FindSessionArtifact(
+ ctx context.Context, sessionID, messageID string, position int,
+) (*types.MessageArtifactRecord, error) {
+ if sessionID == "" || messageID == "" || position < 0 {
+ return nil, nil
+ }
+ var row types.MessageArtifactRecord
+ 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 = ? AND ma.message_id = ? AND ma.position = ? AND ma.deleted_at IS NULL",
+ sessionID, messageID, position).
+ Take(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return &row, nil
+}
+
+// FindSessionArtifactVersions returns every live row of the session that shares
+// sourcePath, i.e. the regenerations the artifact library folds into one entry.
+// An empty sourcePath has no version group — the artifact stands alone — so the
+// caller gets nothing back and deletes just the row it started from.
+func (r *messageRepository) FindSessionArtifactVersions(
+ ctx context.Context, sessionID, sourcePath string,
+) ([]types.MessageArtifactRecord, error) {
+ if sessionID == "" || sourcePath == "" {
+ 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 = ? AND ma.source_path = ? AND ma.deleted_at IS NULL", sessionID, sourcePath).
+ Order("ma.created_at ASC, ma.id ASC").
+ Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ return rows, nil
+}
+
+// SoftDeleteSessionArtifacts tombstones the given rows and returns the subset it
+// actually marked. Rows another caller already tombstoned are left out, so the
+// caller reclaims exactly the blobs it took ownership of and a concurrent
+// duplicate delete reclaims none of them twice.
+//
+// url is left on the tombstone on purpose: if the blob reclaim that follows
+// fails, the storage path is still on record for a later GC pass.
+func (r *messageRepository) SoftDeleteSessionArtifacts(
+ ctx context.Context, sessionID string, refs []types.ArtifactRef, at time.Time,
+) ([]types.ArtifactRef, error) {
+ if sessionID == "" || len(refs) == 0 {
+ return nil, nil
+ }
+ marked := make([]types.ArtifactRef, 0, len(refs))
+ // All or nothing. Deleting a file's versions is several statements, and a
+ // failure partway through would leave some versions hidden from every
+ // listing with their bytes never reclaimed, while the caller reports an
+ // error and the user's retry 404s on the row that did get marked.
+ err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ marked = marked[:0]
+ // One statement per ref: the pairs are a handful at most (a message's
+ // artifacts, or one file's versions), and a composite IN list is not
+ // portable across PostgreSQL and SQLite.
+ for _, ref := range refs {
+ if ref.MessageID == "" || ref.Position < 0 {
+ continue
+ }
+ res := tx.Model(&types.MessageArtifactRecord{}).
+ Where("session_id = ? AND message_id = ? AND position = ? AND deleted_at IS NULL",
+ sessionID, ref.MessageID, ref.Position).
+ Update("deleted_at", at.UTC())
+ if res.Error != nil {
+ return res.Error
+ }
+ if res.RowsAffected > 0 {
+ marked = append(marked, ref)
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ return marked, nil
+}
+
+// CountLiveArtifactsByURL counts artifact rows that still point at a stored
+// object and have not been deleted, across every session.
+//
+// It is the last guard before a delete reclaims bytes. The catalog's binding
+// count is the primary one, but it does not cover every way two rows come to
+// share a URL: a forked session's copied rows carry the parent's storage URLs
+// without a binding of their own (CreateForked copies the rows, it does not
+// re-Bind them), a deployment may store raw provider paths that the catalog
+// never registered, and a later answer that re-attaches an earlier file writes
+// another row with the same URL. Any of those still needs the bytes.
+//
+// Soft-deleted messages are counted on purpose: their rows can come back, and
+// keeping a blob costs less than a restored message pointing at nothing.
+func (r *messageRepository) CountLiveArtifactsByURL(ctx context.Context, url string) (int64, error) {
+ if url == "" {
+ return 0, nil
+ }
+ var count int64
+ if err := r.db.WithContext(ctx).
+ Model(&types.MessageArtifactRecord{}).
+ Where("url = ? AND deleted_at IS NULL", url).
+ Count(&count).Error; err != nil {
+ return 0, err
+ }
+ return count, nil
+}
diff --git a/internal/application/repository/message_artifact_delete_test.go b/internal/application/repository/message_artifact_delete_test.go
new file mode 100644
index 000000000..96b9a9249
--- /dev/null
+++ b/internal/application/repository/message_artifact_delete_test.go
@@ -0,0 +1,342 @@
+package repository
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/stretchr/testify/require"
+)
+
+// Deleting an artifact must not renumber the ones after it: position is the
+// index the download endpoint addresses a file by, so a shift would hand an
+// existing link the wrong blob.
+func TestSoftDeleteKeepsPositionsStable(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),
+ testArtifact("c.pptx", "/w/c.pptx", created),
+ },
+ })
+ require.NoError(t, err)
+
+ marked, err := repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: msg.ID, Position: 1}}, created)
+ require.NoError(t, err)
+ require.Equal(t, []types.ArtifactRef{{MessageID: msg.ID, Position: 1}}, marked)
+
+ got, err := repo.GetMessage(ctx, "s1", msg.ID)
+ require.NoError(t, err)
+ // GORM only soft-deletes for fields typed gorm.DeletedAt. Ours is a plain
+ // *time.Time precisely so the tombstone keeps loading and holding its slot.
+ require.Len(t, got.Artifacts, 3, "the tombstone keeps its slot in the list")
+ require.False(t, got.Artifacts[0].Deleted())
+ require.True(t, got.Artifacts[1].Deleted())
+ require.Equal(t, "c.pptx", got.Artifacts[2].FileName, "index 2 still addresses the third file")
+
+ require.Equal(t, types.MessageArtifacts{got.Artifacts[0], got.Artifacts[2]}, got.Artifacts.Live())
+}
+
+// The collector de-duplicates sandbox files against the session's rows. The
+// tombstone has to stay in that set, or the next collect re-attaches the file
+// the user just deleted — its sandbox mtime has not moved.
+func TestSoftDeletedArtifactsStayInSessionDedupSet(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)},
+ })
+ require.NoError(t, err)
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
+ require.NoError(t, err)
+
+ all, err := repo.GetSessionArtifacts(ctx, "s1")
+ require.NoError(t, err)
+ require.Len(t, all, 1)
+ require.True(t, all[0].Deleted())
+ require.Equal(t, "/w/a.pptx", all[0].SourcePath, "source path and mtime survive for de-duplication")
+ require.Empty(t, all.Live())
+}
+
+// Rewriting a message's artifacts (any UpdateMessage carrying a non-nil list)
+// goes through the same slice, so the tombstone has to round-trip.
+func TestWriteMessageArtifactsPreservesTombstones(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)
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
+ require.NoError(t, err)
+
+ reloaded, err := repo.GetMessage(ctx, "s1", msg.ID)
+ require.NoError(t, err)
+ reloaded.Content = "edited"
+ require.NoError(t, repo.UpdateMessage(ctx, reloaded))
+
+ got, err := repo.GetMessage(ctx, "s1", msg.ID)
+ require.NoError(t, err)
+ require.Len(t, got.Artifacts, 2)
+ require.True(t, got.Artifacts[0].Deleted(), "the tombstone survives a message rewrite")
+ require.False(t, got.Artifacts[1].Deleted())
+}
+
+func TestFindSessionArtifactSkipsTombstones(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)},
+ })
+ require.NoError(t, err)
+
+ found, err := repo.FindSessionArtifact(ctx, "s1", msg.ID, 0)
+ require.NoError(t, err)
+ require.NotNil(t, found)
+ require.Equal(t, "a.pptx", found.FileName)
+
+ missing, err := repo.FindSessionArtifact(ctx, "s1", msg.ID, 9)
+ require.NoError(t, err)
+ require.Nil(t, missing)
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
+ require.NoError(t, err)
+
+ gone, err := repo.FindSessionArtifact(ctx, "s1", msg.ID, 0)
+ require.NoError(t, err)
+ require.Nil(t, gone, "a tombstone reads as absent, so a second delete is a 404")
+
+ // And a second delete claims nothing, so its caller reclaims no blobs.
+ marked, err := repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
+ require.NoError(t, err)
+ require.Empty(t, marked, "a second delete claims nothing, so its caller reclaims no blobs")
+}
+
+// Versions are the rows of one session sharing a sandbox path — what the
+// artifact library folds into a single entry with a version count.
+func TestFindSessionArtifactVersions(t *testing.T) {
+ db := newArtifactTestDB(t)
+ repo := NewMessageRepository(db)
+ ctx := context.Background()
+ base := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
+
+ first, err := repo.CreateMessage(ctx, &types.Message{
+ SessionID: "s1", RequestID: "r1", Role: "assistant", CreatedAt: base,
+ Artifacts: types.MessageArtifacts{testArtifact("report.pptx", "/w/report.pptx", base)},
+ })
+ require.NoError(t, err)
+ v2 := testArtifact("report.pptx", "/w/report.pptx", base.Add(time.Hour))
+ v2.URL = "local://blobs/report-v2.pptx"
+ _, err = repo.CreateMessage(ctx, &types.Message{
+ SessionID: "s1", RequestID: "r2", Role: "assistant", CreatedAt: base.Add(time.Hour),
+ Artifacts: types.MessageArtifacts{v2, testArtifact("other.csv", "/w/other.csv", base)},
+ })
+ require.NoError(t, err)
+ // Another session's file at the same sandbox path is a different file.
+ _, err = repo.CreateMessage(ctx, &types.Message{
+ SessionID: "s2", RequestID: "r3", Role: "assistant", CreatedAt: base,
+ Artifacts: types.MessageArtifacts{testArtifact("report.pptx", "/w/report.pptx", base)},
+ })
+ require.NoError(t, err)
+
+ versions, err := repo.FindSessionArtifactVersions(ctx, "s1", "/w/report.pptx")
+ require.NoError(t, err)
+ require.Len(t, versions, 2)
+
+ // An artifact with no sandbox path has no version group.
+ none, err := repo.FindSessionArtifactVersions(ctx, "s1", "")
+ require.NoError(t, err)
+ require.Empty(t, none)
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: first.ID, Position: 0}}, base)
+ require.NoError(t, err)
+ versions, err = repo.FindSessionArtifactVersions(ctx, "s1", "/w/report.pptx")
+ require.NoError(t, err)
+ require.Len(t, versions, 1, "already-deleted versions drop out")
+}
+
+func TestListArtifactLibraryHidesDeletedArtifacts(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: "我的会话"})
+
+ first, err := repo.CreateMessage(ctx, &types.Message{
+ SessionID: mine, RequestID: "r1", Role: "assistant", CreatedAt: base,
+ Artifacts: types.MessageArtifacts{testArtifact("report.pptx", "/w/report.pptx", base)},
+ })
+ require.NoError(t, err)
+ v2 := testArtifact("report.pptx", "/w/report.pptx", base.Add(time.Hour))
+ v2.URL = "local://blobs/report-v2.pptx"
+ latest, err := repo.CreateMessage(ctx, &types.Message{
+ SessionID: mine, RequestID: "r2", Role: "assistant", CreatedAt: base.Add(time.Hour),
+ Artifacts: types.MessageArtifacts{v2},
+ })
+ require.NoError(t, err)
+
+ query := &types.ArtifactLibraryQuery{TenantID: 7, UserID: "alice", Page: 1, PageSize: 20}
+ items, total, err := repo.ListArtifactLibrary(ctx, query)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, total)
+ require.Equal(t, 2, items[0].VersionCount)
+
+ // Deleting only the newest version surfaces the one before it — which is
+ // why the delete path tombstones every version of a library row at once.
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, mine,
+ []types.ArtifactRef{{MessageID: latest.ID, Position: 0}}, base)
+ require.NoError(t, err)
+ items, total, err = repo.ListArtifactLibrary(ctx, query)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, total)
+ require.Equal(t, first.ID, items[0].MessageID)
+ require.Equal(t, 1, items[0].VersionCount)
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, mine,
+ []types.ArtifactRef{{MessageID: first.ID, Position: 0}}, base)
+ require.NoError(t, err)
+ items, total, err = repo.ListArtifactLibrary(ctx, query)
+ require.NoError(t, err)
+ require.EqualValues(t, 0, total)
+ require.Empty(t, items)
+}
+
+// A stale writer must not be able to undo a delete. writeMessageArtifacts is a
+// full replace, so a caller holding a pre-delete snapshot would resurrect the
+// row while its bytes are already being reclaimed.
+func TestWriteMessageArtifactsCannotResurrectATombstone(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)
+ // A snapshot taken before the delete, still carrying both as live.
+ stale, err := repo.GetMessage(ctx, "s1", msg.ID)
+ require.NoError(t, err)
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: msg.ID, Position: 0}}, created)
+ require.NoError(t, err)
+
+ stale.Content = "edited"
+ require.NoError(t, repo.UpdateMessage(ctx, stale))
+
+ got, err := repo.GetMessage(ctx, "s1", msg.ID)
+ require.NoError(t, err)
+ require.Len(t, got.Artifacts, 2)
+ require.True(t, got.Artifacts[0].Deleted(), "the stale write must not bring the deleted row back")
+ require.False(t, got.Artifacts[1].Deleted())
+}
+
+// Deleting a file's versions is several statements; a failure partway through
+// must not leave some of them hidden with their bytes never reclaimed.
+func TestSoftDeleteSessionArtifactsIsAtomic(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)
+
+ // Dropping the table mid-transaction is the cheapest way to make the
+ // second statement fail after the first one succeeded.
+ require.NoError(t, db.Exec(
+ `CREATE TRIGGER fail_second BEFORE UPDATE ON message_artifacts
+ WHEN NEW.position = 1
+ BEGIN SELECT RAISE(ABORT, 'boom'); END`).Error)
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1", []types.ArtifactRef{
+ {MessageID: msg.ID, Position: 0},
+ {MessageID: msg.ID, Position: 1},
+ }, created)
+ require.Error(t, err)
+
+ require.NoError(t, db.Exec("DROP TRIGGER fail_second").Error)
+ got, err := repo.GetMessage(ctx, "s1", msg.ID)
+ require.NoError(t, err)
+ require.False(t, got.Artifacts[0].Deleted(), "the first mark must roll back with the failed second one")
+ require.False(t, got.Artifacts[1].Deleted())
+}
+
+// The last guard before reclaiming bytes: a fork's copied rows carry the
+// parent's storage URLs without a binding of their own.
+func TestCountLiveArtifactsByURLSpansSessions(t *testing.T) {
+ db := newArtifactTestDB(t)
+ repo := NewMessageRepository(db)
+ ctx := context.Background()
+ created := time.Date(2026, 9, 1, 2, 0, 0, 0, time.UTC)
+
+ shared := testArtifact("report.pptx", "/w/report.pptx", created)
+ parent, err := repo.CreateMessage(ctx, &types.Message{
+ SessionID: "s1", RequestID: "r1", Role: "assistant",
+ Artifacts: types.MessageArtifacts{shared},
+ })
+ require.NoError(t, err)
+ // The fork copy: new session and message, same storage URL.
+ forked, err := repo.CreateMessage(ctx, &types.Message{
+ SessionID: "s2", RequestID: "r2", Role: "assistant",
+ Artifacts: types.MessageArtifacts{shared},
+ })
+ require.NoError(t, err)
+
+ count, err := repo.CountLiveArtifactsByURL(ctx, shared.URL)
+ require.NoError(t, err)
+ require.EqualValues(t, 2, count)
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s1",
+ []types.ArtifactRef{{MessageID: parent.ID, Position: 0}}, created)
+ require.NoError(t, err)
+ count, err = repo.CountLiveArtifactsByURL(ctx, shared.URL)
+ require.NoError(t, err)
+ require.EqualValues(t, 1, count, "the fork still needs the bytes")
+
+ _, err = repo.SoftDeleteSessionArtifacts(ctx, "s2",
+ []types.ArtifactRef{{MessageID: forked.ID, Position: 0}}, created)
+ require.NoError(t, err)
+ count, err = repo.CountLiveArtifactsByURL(ctx, shared.URL)
+ require.NoError(t, err)
+ require.EqualValues(t, 0, count, "now nothing points at them")
+}
diff --git a/internal/application/service/artifact_collector.go b/internal/application/service/artifact_collector.go
index 18b6d5d82..69b737a75 100644
--- a/internal/application/service/artifact_collector.go
+++ b/internal/application/service/artifact_collector.go
@@ -378,6 +378,10 @@ func (c *ArtifactCollector) loadKnownSet(ctx context.Context, sessionID string)
return set
}
for _, p := range prev {
+ if p.Deleted() {
+ set.rememberDeleted(p)
+ continue
+ }
set.remember(p)
}
return set
@@ -551,6 +555,10 @@ func (c *ArtifactCollector) bindArtifactResource(ctx context.Context, ref, messa
// sandbox back at an earlier commit, so every unchanged file is de-duplicated
// out of that turn's own artifact list — and the reference still has to be bound
// to that file's stable handle.
+//
+// Files the user deleted are filtered out: they are still in the store as
+// tombstones so loadKnownSet will not re-collect them, but an answer must not
+// resolve a name to a file whose bytes are gone.
func (c *ArtifactCollector) SessionArtifacts(ctx context.Context, sessionID string) types.MessageArtifacts {
if c == nil || c.store == nil || sessionID == "" {
return nil
@@ -560,7 +568,7 @@ func (c *ArtifactCollector) SessionArtifacts(ctx context.Context, sessionID stri
logger.Warnf(ctx, "Read session artifacts failed: %v", err)
return nil
}
- return previous
+ return types.MessageArtifacts(previous).Live()
}
// BindArtifactsToMessage makes messageID an owner of each artifact's resource
@@ -640,6 +648,26 @@ func (k *artifactKnownSet) remember(art types.MessageArtifact) {
}
}
+// rememberDeleted registers a tombstone: a file the user deleted, whose sandbox
+// copy may still be sitting there untouched.
+//
+// Only the (path, mtime) key goes in. That is what stops an unchanged sandbox
+// file being re-collected, which is the whole reason tombstones stay in the
+// known set. The content hash is deliberately left out, and so is byPath: those
+// two drive the same-content short circuit in knownSameContent, and a turn that
+// rewrites the file with identical bytes is a genuine regeneration the user
+// should get back — not a restore to skip. Keeping the hash here would make a
+// deleted file impossible to reproduce byte-for-byte ever again.
+func (k *artifactKnownSet) rememberDeleted(art types.MessageArtifact) {
+ if k == nil {
+ return
+ }
+ if k.keys == nil {
+ k.keys = map[string]struct{}{}
+ }
+ k.keys[artifactKey(art.SourcePath, art.ModTime)] = struct{}{}
+}
+
func (k *artifactKnownSet) seenMtime(path string, mod time.Time) bool {
if k == nil {
return false
diff --git a/internal/application/service/artifact_collector_test.go b/internal/application/service/artifact_collector_test.go
index 5e44cf5d6..b79d5c09c 100644
--- a/internal/application/service/artifact_collector_test.go
+++ b/internal/application/service/artifact_collector_test.go
@@ -803,3 +803,126 @@ func bytesN(n int) []byte {
}
return b
}
+
+// A deleted file whose sandbox copy was never touched must stay gone: its
+// mtime has not moved, so nothing about the sandbox says it was regenerated.
+func TestArtifactCollector_DeletedFileDoesNotComeBackUntouched(t *testing.T) {
+ ctx := context.Background()
+ mod := mustParseTime("2026-07-10T10:20:33Z")
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {
+ Name: "report.pptx", Path: "/workspace/output/report.pptx",
+ Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mod,
+ },
+ },
+ },
+ contents: map[string][]byte{"/workspace/output/report.pptx": []byte("PPTX")},
+ }
+ deletedAt := mustParseTime("2026-07-11T00:00:00Z")
+ store := &fakeStore{prev: []types.MessageArtifact{{
+ SourcePath: "/workspace/output/report.pptx",
+ ModTime: mod,
+ FileSize: 4,
+ ContentHash: artifactContentHash([]byte("PPTX")),
+ DeletedAt: &deletedAt,
+ }}}
+ fs := &fakeFileService{}
+ c := newTestCollector(src, store, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-2", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0: an untouched sandbox file must not resurrect it", len(got))
+ }
+ if len(fs.saved) != 0 {
+ t.Fatalf("SaveBytes should not have been called; saved=%v", fs.saved)
+ }
+}
+
+// But a turn that actually rewrites the file — new mtime — regenerates it, and
+// the user gets it back even when the bytes come out identical. The tombstone
+// must not feed the same-content restore short circuit: doing so would make a
+// deleted file impossible to reproduce byte-for-byte ever again.
+func TestArtifactCollector_DeletedFileReturnsWhenRegenerated(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {
+ Name: "report.pptx", Path: "/workspace/output/report.pptx",
+ Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-11T09:00:00Z"),
+ },
+ },
+ },
+ contents: map[string][]byte{"/workspace/output/report.pptx": []byte("PPTX")},
+ }
+ deletedAt := mustParseTime("2026-07-11T00:00:00Z")
+ store := &fakeStore{prev: []types.MessageArtifact{{
+ SourcePath: "/workspace/output/report.pptx",
+ ModTime: mustParseTime("2026-07-10T10:20:33Z"),
+ FileSize: 4,
+ // Identical content to what the sandbox now holds.
+ ContentHash: artifactContentHash([]byte("PPTX")),
+ DeletedAt: &deletedAt,
+ }}}
+ fs := &fakeFileService{}
+ c := newTestCollector(src, store, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-2", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 1 {
+ t.Fatalf("Collect() len = %d, want 1: a regenerated file is a new artifact, not a restore", len(got))
+ }
+ if got[0].Deleted() {
+ t.Fatal("the re-collected artifact must be live, not a tombstone")
+ }
+ if len(fs.saved) != 1 {
+ t.Fatalf("the regenerated bytes must be uploaded; saved=%v", fs.saved)
+ }
+}
+
+// A live artifact's same-content restore still short-circuits — the tombstone
+// change must not weaken the fork-checkout path it was built for.
+func TestArtifactCollector_LiveRestoreStillSkipsAlongsideATombstone(t *testing.T) {
+ ctx := context.Background()
+ src := &fakeSandboxSource{
+ entries: map[string][]sandbox.RemoteDirEntry{
+ "sess-1": {
+ {
+ Name: "report.pptx", Path: "/workspace/output/report.pptx",
+ Type: sandbox.RemoteEntryFile, Size: 4, ModTime: mustParseTime("2026-07-11T09:00:00Z"),
+ },
+ },
+ },
+ contents: map[string][]byte{"/workspace/output/report.pptx": []byte("PPTX")},
+ }
+ deletedAt := mustParseTime("2026-07-11T00:00:00Z")
+ store := &fakeStore{prev: []types.MessageArtifact{
+ // An older version of the same file that the user deleted...
+ {
+ SourcePath: "/workspace/output/report.pptx", ModTime: mustParseTime("2026-07-09T10:00:00Z"),
+ FileSize: 4, ContentHash: artifactContentHash([]byte("OLD!")), DeletedAt: &deletedAt,
+ },
+ // ...and a live one whose bytes match what the sandbox holds now.
+ {
+ SourcePath: "/workspace/output/report.pptx", ModTime: mustParseTime("2026-07-10T10:20:33Z"),
+ FileSize: 4, ContentHash: artifactContentHash([]byte("PPTX")),
+ },
+ }}
+ fs := &fakeFileService{}
+ c := newTestCollector(src, store, fs, 1<<20)
+
+ got, err := c.Collect(ctx, "sess-1", "msg-2", 42, "/workspace/output")
+ if err != nil {
+ t.Fatalf("Collect() error = %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("Collect() len = %d, want 0: the live version still matches, so this is a restore", len(got))
+ }
+}
diff --git a/internal/application/service/message_artifact_delete.go b/internal/application/service/message_artifact_delete.go
new file mode 100644
index 000000000..04af6daa1
--- /dev/null
+++ b/internal/application/service/message_artifact_delete.go
@@ -0,0 +1,178 @@
+package service
+
+import (
+ "context"
+ "slices"
+ "time"
+
+ "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+)
+
+// ErrArtifactNotFound is returned when the addressed artifact does not exist,
+// belongs to a message that is gone, or was already deleted. Handlers map it to
+// 404 so a caller cannot probe which of the three it was.
+var ErrArtifactNotFound = errors.NewNotFoundError("artifact not found")
+
+// DeleteSessionArtifact removes a skill-generated file from the session.
+//
+// The row is tombstoned rather than dropped. Position is the index the download
+// endpoint addresses a file by, so removing a row would shift every later file
+// in the message and hand an old link the wrong blob; and the tombstone is what
+// keeps ArtifactCollector from re-attaching the sandbox copy, whose mtime has
+// not changed just because the user deleted the stored version.
+//
+// The bytes are a separate concern: this method reports them in Reclaim and the
+// caller — which has the tenant's file service and the resource catalog —
+// releases the binding and deletes the object. Doing it here would mean giving
+// the message service a storage dependency it otherwise has no use for.
+//
+// Reclaim must run only after this returns. A failed reclaim leaves an orphaned
+// blob that a GC pass can still find through the tombstone's url; a reclaim
+// that ran first could delete bytes for a tombstone that was never written.
+func (s *messageService) DeleteSessionArtifact(
+ ctx context.Context, req *types.ArtifactDeleteRequest,
+) (*types.ArtifactDeleteResult, error) {
+ if req == nil || req.SessionID == "" || req.MessageID == "" || req.Index < 0 {
+ return nil, errors.NewBadRequestError("session_id, message_id and index are required")
+ }
+
+ // Ownership: the session must belong to the caller. Deleting is not covered
+ // by the shared-agent read access the download endpoint honours — a viewer
+ // of someone else's shared session may fetch a file, not destroy it.
+ tenantID := types.MustTenantIDFromContext(ctx)
+ if _, err := s.sessionRepo.Get(ctx, tenantID, sessionUserIDForLookup(ctx), req.SessionID); err != nil {
+ return nil, err
+ }
+
+ target, err := s.messageRepo.FindSessionArtifact(ctx, req.SessionID, req.MessageID, req.Index)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "session_id": req.SessionID,
+ "message_id": req.MessageID,
+ "index": req.Index,
+ })
+ return nil, err
+ }
+ if target == nil {
+ return nil, ErrArtifactNotFound
+ }
+
+ rows, err := s.artifactDeleteSet(ctx, req, *target)
+ if err != nil {
+ return nil, err
+ }
+
+ refs := make([]types.ArtifactRef, 0, len(rows))
+ for _, row := range rows {
+ refs = append(refs, types.ArtifactRef{MessageID: row.MessageID, Position: row.Position})
+ }
+ marked, err := s.messageRepo.SoftDeleteSessionArtifacts(ctx, req.SessionID, refs, time.Now())
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "session_id": req.SessionID,
+ "message_id": req.MessageID,
+ })
+ return nil, err
+ }
+ if len(marked) == 0 {
+ // A concurrent delete tombstoned these rows first. It owns the reclaim.
+ return nil, ErrArtifactNotFound
+ }
+
+ logger.Infof(ctx, "Deleted artifact %s from session %s: %d row(s)",
+ target.FileName, req.SessionID, len(marked))
+ return &types.ArtifactDeleteResult{
+ FileName: target.FileName,
+ Deleted: len(marked),
+ // Only the rows this call claimed: a row a concurrent delete marked
+ // first is its reclaim to do, and doing it twice would try to remove
+ // the same object from under it.
+ Reclaim: s.reclaimableBlobs(ctx, artifactReclaimList(rows, marked)),
+ }, nil
+}
+
+// reclaimableBlobs drops the objects some other row still points at.
+//
+// The catalog's binding count is the primary guard, but it only knows about
+// bindings, and rows come to share a URL in ways that never created one: a
+// forked session's rows are copies of the parent's, storage URL included, and
+// CreateForked does not re-Bind them; a deployment storing raw provider paths
+// has no catalog entries at all. Deleting in the parent session would then take
+// the bytes out from under the fork. A count of live rows catches all of it.
+//
+// A failed count keeps the blob, like every other uncertainty on this path.
+func (s *messageService) reclaimableBlobs(
+ ctx context.Context, candidates []types.ArtifactBlobRef,
+) []types.ArtifactBlobRef {
+ out := make([]types.ArtifactBlobRef, 0, len(candidates))
+ for _, ref := range candidates {
+ live, err := s.messageRepo.CountLiveArtifactsByURL(ctx, ref.URL)
+ if err != nil {
+ logger.Warnf(ctx, "Artifact reclaim check failed for %s, keeping the blob: %v", ref.URL, err)
+ continue
+ }
+ if live > 0 {
+ logger.Infof(ctx, "Keeping artifact blob %s: %d live row(s) still point at it", ref.URL, live)
+ continue
+ }
+ out = append(out, ref)
+ }
+ return out
+}
+
+// artifactDeleteSet expands the request into the rows to tombstone: the one
+// addressed row, or every live version of the same sandbox file when the caller
+// asked for all of them. An artifact with no source path has no version group —
+// nothing else in the session is the "same file" — so it deletes alone.
+func (s *messageService) artifactDeleteSet(
+ ctx context.Context, req *types.ArtifactDeleteRequest, target types.MessageArtifactRecord,
+) ([]types.MessageArtifactRecord, error) {
+ if !req.AllVersions || target.SourcePath == "" {
+ return []types.MessageArtifactRecord{target}, nil
+ }
+ versions, err := s.messageRepo.FindSessionArtifactVersions(ctx, req.SessionID, target.SourcePath)
+ if err != nil {
+ logger.ErrorWithFields(ctx, err, map[string]interface{}{
+ "session_id": req.SessionID,
+ "source_path": target.SourcePath,
+ })
+ return nil, err
+ }
+ if len(versions) == 0 {
+ return []types.MessageArtifactRecord{target}, nil
+ }
+ return versions, nil
+}
+
+// artifactReclaimList groups the rows this call tombstoned by the object behind
+// them. A later answer that re-attaches an earlier file stores another row with
+// the same URL and its own resource binding, so one object can come from
+// several messages: the bytes are reclaimed once, but every one of those
+// messages has to give up its claim first.
+func artifactReclaimList(
+ rows []types.MessageArtifactRecord, marked []types.ArtifactRef,
+) []types.ArtifactBlobRef {
+ claimed := make(map[types.ArtifactRef]bool, len(marked))
+ for _, ref := range marked {
+ claimed[ref] = true
+ }
+ at := make(map[string]int, len(rows))
+ out := make([]types.ArtifactBlobRef, 0, len(rows))
+ for _, row := range rows {
+ if row.URL == "" || !claimed[(types.ArtifactRef{MessageID: row.MessageID, Position: row.Position})] {
+ continue
+ }
+ i, ok := at[row.URL]
+ if !ok {
+ at[row.URL] = len(out)
+ out = append(out, types.ArtifactBlobRef{URL: row.URL, MessageIDs: []string{row.MessageID}})
+ continue
+ }
+ if !slices.Contains(out[i].MessageIDs, row.MessageID) {
+ out[i].MessageIDs = append(out[i].MessageIDs, row.MessageID)
+ }
+ }
+ return out
+}
diff --git a/internal/application/service/message_artifact_delete_test.go b/internal/application/service/message_artifact_delete_test.go
new file mode 100644
index 000000000..b2a7c7042
--- /dev/null
+++ b/internal/application/service/message_artifact_delete_test.go
@@ -0,0 +1,201 @@
+package service
+
+import (
+ "context"
+ stderrors "errors"
+ "testing"
+ "time"
+
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/stretchr/testify/require"
+)
+
+type deleteSessionRepo struct {
+ interfaces.SessionRepository
+ gotTenant uint64
+ gotUser string
+ err error
+}
+
+func (r *deleteSessionRepo) Get(_ context.Context, tenantID uint64, userID, id string) (*types.Session, error) {
+ r.gotTenant, r.gotUser = tenantID, userID
+ if r.err != nil {
+ return nil, r.err
+ }
+ return &types.Session{ID: id, TenantID: tenantID}, nil
+}
+
+type deleteMessageRepo struct {
+ interfaces.MessageRepository
+ target *types.MessageArtifactRecord
+ versions []types.MessageArtifactRecord
+ marked []types.ArtifactRef
+ liveByte map[string]int64
+ liveErr error
+ askedURL []string
+}
+
+func (r *deleteMessageRepo) FindSessionArtifact(
+ _ context.Context, _, _ string, _ int,
+) (*types.MessageArtifactRecord, error) {
+ return r.target, nil
+}
+
+func (r *deleteMessageRepo) FindSessionArtifactVersions(
+ _ context.Context, _, _ string,
+) ([]types.MessageArtifactRecord, error) {
+ return r.versions, nil
+}
+
+func (r *deleteMessageRepo) SoftDeleteSessionArtifacts(
+ _ context.Context, _ string, refs []types.ArtifactRef, _ time.Time,
+) ([]types.ArtifactRef, error) {
+ if r.marked != nil {
+ return r.marked, nil
+ }
+ return refs, nil
+}
+
+func (r *deleteMessageRepo) CountLiveArtifactsByURL(_ context.Context, url string) (int64, error) {
+ r.askedURL = append(r.askedURL, url)
+ if r.liveErr != nil {
+ return 0, r.liveErr
+ }
+ return r.liveByte[url], nil
+}
+
+func deleteCallerCtx() context.Context {
+ ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
+ return context.WithValue(ctx, types.UserIDContextKey, "alice")
+}
+
+func artifactRow(messageID string, pos int, url, path string) types.MessageArtifactRecord {
+ return types.MessageArtifactRecord{
+ MessageID: messageID, Position: pos, URL: url, SourcePath: path, FileName: "report.pptx",
+ }
+}
+
+// Deleting is a write on the session, so it is scoped to its owner — unlike the
+// download path, which also honours shared-agent read access.
+func TestDeleteSessionArtifactIsScopedToTheSessionOwner(t *testing.T) {
+ sessions := &deleteSessionRepo{}
+ repo := &deleteMessageRepo{target: ptr(artifactRow("msg-1", 0, "resource://a", "/w/a.pptx"))}
+ s := &messageService{sessionRepo: sessions, messageRepo: repo}
+
+ _, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0,
+ })
+ require.NoError(t, err)
+ require.EqualValues(t, 7, sessions.gotTenant)
+ require.Equal(t, "alice", sessions.gotUser, "the owner check must carry the caller, not a tenant-wide lookup")
+}
+
+func TestDeleteSessionArtifactRejectsSomeoneElsesSession(t *testing.T) {
+ sessions := &deleteSessionRepo{err: apperrors.ErrSessionNotFound}
+ repo := &deleteMessageRepo{target: ptr(artifactRow("msg-1", 0, "resource://a", "/w/a.pptx"))}
+ s := &messageService{sessionRepo: sessions, messageRepo: repo}
+
+ _, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0,
+ })
+ require.ErrorIs(t, err, apperrors.ErrSessionNotFound)
+ require.Empty(t, repo.askedURL, "a rejected caller must not reach the reclaim path at all")
+}
+
+func TestDeleteSessionArtifactMissingOrAlreadyDeleted(t *testing.T) {
+ s := &messageService{sessionRepo: &deleteSessionRepo{}, messageRepo: &deleteMessageRepo{target: nil}}
+ _, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0,
+ })
+ require.ErrorIs(t, err, ErrArtifactNotFound)
+
+ // Nothing claimed means a concurrent delete got there first; it owns the reclaim.
+ repo := &deleteMessageRepo{
+ target: ptr(artifactRow("msg-1", 0, "resource://a", "/w/a.pptx")),
+ marked: []types.ArtifactRef{},
+ }
+ s = &messageService{sessionRepo: &deleteSessionRepo{}, messageRepo: repo}
+ _, err = s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0,
+ })
+ require.ErrorIs(t, err, ErrArtifactNotFound)
+ require.Empty(t, repo.askedURL)
+}
+
+// A forked session's rows are copies of the parent's, storage URL included, and
+// CreateForked does not give them their own catalog binding. Deleting in the
+// parent must not pull the bytes out from under the fork.
+func TestDeleteSessionArtifactKeepsBytesAnotherRowStillNeeds(t *testing.T) {
+ repo := &deleteMessageRepo{
+ target: ptr(artifactRow("msg-1", 0, "resource://shared", "/w/a.pptx")),
+ liveByte: map[string]int64{"resource://shared": 1},
+ }
+ s := &messageService{sessionRepo: &deleteSessionRepo{}, messageRepo: repo}
+
+ result, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0,
+ })
+ require.NoError(t, err)
+ require.Equal(t, 1, result.Deleted, "the row is still removed from every listing")
+ require.Empty(t, result.Reclaim, "but its bytes stay: a live row elsewhere still points at them")
+}
+
+// An unreadable count keeps the blob, like every other uncertainty here.
+func TestDeleteSessionArtifactKeepsBytesWhenTheGuardFails(t *testing.T) {
+ repo := &deleteMessageRepo{
+ target: ptr(artifactRow("msg-1", 0, "resource://a", "/w/a.pptx")),
+ liveErr: stderrors.New("db down"),
+ }
+ s := &messageService{sessionRepo: &deleteSessionRepo{}, messageRepo: repo}
+
+ result, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0,
+ })
+ require.NoError(t, err)
+ require.Empty(t, result.Reclaim)
+}
+
+// all_versions collapses the versions to distinct objects, and each object
+// carries every deleted message that owned it so all their bindings go.
+func TestDeleteSessionArtifactAllVersionsGroupsOwnersPerObject(t *testing.T) {
+ repo := &deleteMessageRepo{
+ target: ptr(artifactRow("msg-1", 0, "resource://v1", "/w/report.pptx")),
+ versions: []types.MessageArtifactRecord{
+ artifactRow("msg-1", 0, "resource://v1", "/w/report.pptx"),
+ artifactRow("msg-2", 0, "resource://v2", "/w/report.pptx"),
+ // A later answer re-attached v1; same object, another owner.
+ artifactRow("msg-3", 1, "resource://v1", "/w/report.pptx"),
+ },
+ }
+ s := &messageService{sessionRepo: &deleteSessionRepo{}, messageRepo: repo}
+
+ result, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 0, AllVersions: true,
+ })
+ require.NoError(t, err)
+ require.Equal(t, 3, result.Deleted)
+ require.Len(t, result.Reclaim, 2, "three rows, two distinct objects")
+ byURL := map[string][]string{}
+ for _, ref := range result.Reclaim {
+ byURL[ref.URL] = ref.MessageIDs
+ }
+ require.ElementsMatch(t, []string{"msg-1", "msg-3"}, byURL["resource://v1"])
+ require.Equal(t, []string{"msg-2"}, byURL["resource://v2"])
+}
+
+// An artifact with no sandbox path has no version group, so all_versions is a
+// no-op rather than a session-wide sweep of every pathless file.
+func TestDeleteSessionArtifactAllVersionsWithoutASourcePath(t *testing.T) {
+ repo := &deleteMessageRepo{target: ptr(artifactRow("msg-1", 2, "resource://a", ""))}
+ s := &messageService{sessionRepo: &deleteSessionRepo{}, messageRepo: repo}
+
+ result, err := s.DeleteSessionArtifact(deleteCallerCtx(), &types.ArtifactDeleteRequest{
+ SessionID: "sess-1", MessageID: "msg-1", Index: 2, AllVersions: true,
+ })
+ require.NoError(t, err)
+ require.Equal(t, 1, result.Deleted)
+}
+
+func ptr[T any](v T) *T { return &v }
diff --git a/internal/application/service/message_artifact_versions.go b/internal/application/service/message_artifact_versions.go
index 1483e1b14..39ab60757 100644
--- a/internal/application/service/message_artifact_versions.go
+++ b/internal/application/service/message_artifact_versions.go
@@ -17,7 +17,7 @@ func (s *messageService) clarifyReadArtifactVersions(ctx context.Context, sessio
continue
}
owned := make(map[string]bool)
- for _, artifact := range message.Artifacts {
+ for _, artifact := range message.Artifacts.Live() {
owned[artifact.URL] = true
}
for _, ref := range types.ScanResourceReferences(message.Content) {
@@ -29,11 +29,14 @@ func (s *messageService) clarifyReadArtifactVersions(ctx context.Context, sessio
if !needsHistory {
return messages
}
- previous, err := s.messageRepo.GetSessionArtifacts(ctx, sessionID)
+ stored, err := s.messageRepo.GetSessionArtifacts(ctx, sessionID)
if err != nil {
logger.Warnf(ctx, "Read artifact versions failed: %v", err)
return messages
}
+ // Tombstones carry the URL a past answer referenced, but the file is gone;
+ // clarifying "this is version 2 of 3" about it would be a lie.
+ previous := stored.Live()
result := append([]*types.Message(nil), messages...)
for i, message := range messages {
if message == nil {
@@ -50,7 +53,12 @@ func (s *messageService) clarifyReadArtifactVersions(ctx context.Context, sessio
}
}
copy := *message
- copy.Content = types.ClarifyArtifactVersions(message.Content, message.Artifacts, referenced, types.LanguageFromContextOrDefault(ctx))
+ copy.Content = types.ClarifyArtifactVersions(
+ message.Content,
+ message.Artifacts.Live(),
+ referenced,
+ types.LanguageFromContextOrDefault(ctx),
+ )
result[i] = &copy
}
return result
diff --git a/internal/database/migration_sqlite_versioned_schema_test.go b/internal/database/migration_sqlite_versioned_schema_test.go
index 0e52ac2ea..4c1a25877 100644
--- a/internal/database/migration_sqlite_versioned_schema_test.go
+++ b/internal/database/migration_sqlite_versioned_schema_test.go
@@ -46,9 +46,10 @@ var versionedSQLiteColumns = map[string][]string{
"embed_channels": {"allow_memory"}, // 000060
"mcp_oauth_tokens": {"principal_type", "principal_id"}, // 000064
"mcp_tool_approvals": {"enabled"}, // 000091
+ "message_artifacts": {"deleted_at"}, // 000107
}
-const expectedSQLiteMigrationVersion = 25
+const expectedSQLiteMigrationVersion = 26
func TestSQLiteMigrationsCreateVersionedSchema(t *testing.T) {
repoRoot := sqliteRepoRoot(t)
diff --git a/internal/handler/session/artifact_delete.go b/internal/handler/session/artifact_delete.go
new file mode 100644
index 000000000..ca734cc1f
--- /dev/null
+++ b/internal/handler/session/artifact_delete.go
@@ -0,0 +1,135 @@
+package session
+
+import (
+ stderrors "errors"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/types"
+ secutils "github.com/Tencent/WeKnora/internal/utils"
+ "github.com/gin-gonic/gin"
+)
+
+// DeleteMessageArtifact godoc
+// @Summary 删除会话中的产物文件
+// @Description 删除某条 assistant 消息生成的单个文件;all_versions=true 时连同本会话中该文件的所有历史版本一并删除
+// @Tags 会话
+// @Produce json
+// @Param session_id path string true "会话ID"
+// @Param message_id path string true "消息ID"
+// @Param index path int true "产物在消息中的位置"
+// @Param all_versions query bool false "是否删除该文件的所有版本"
+// @Success 200 {object} map[string]interface{}
+// @Failure 404 {object} errors.AppError
+// @Security Bearer
+// @Router /sessions/{session_id}/messages/{message_id}/artifacts/{index} [delete]
+//
+// Addressed by the same (message, index) coordinates as the download endpoint,
+// so a client deletes exactly the row it was showing. The in-chat panel lists
+// every version separately and omits all_versions; the artifact library folds
+// versions into one entry and sets it.
+func (h *Handler) DeleteMessageArtifact(c *gin.Context) {
+ sessionID := secutils.SanitizeForLog(paramSessionID(c))
+ messageID := secutils.SanitizeForLog(c.Param("message_id"))
+ index, err := strconv.Atoi(c.Param("index"))
+ if err != nil || index < 0 {
+ _ = c.Error(errors.NewBadRequestError("invalid artifact index"))
+ return
+ }
+ h.deleteArtifact(c, &types.ArtifactDeleteRequest{
+ SessionID: sessionID,
+ MessageID: messageID,
+ Index: index,
+ AllVersions: artifactAllVersions(c, false),
+ })
+}
+
+// DeleteLibraryArtifact godoc
+// @Summary 删除产物库中的文件
+// @Description 删除产物库中的一个文件。产物库一行代表一个文件的最新版本,默认连同该文件在本会话中的所有历史版本一并删除
+// @Tags 会话
+// @Produce json
+// @Param session_id query string true "会话ID"
+// @Param message_id query string true "消息ID"
+// @Param index query int true "产物在消息中的位置"
+// @Param all_versions query bool false "是否删除所有版本,默认 true"
+// @Success 200 {object} map[string]interface{}
+// @Failure 404 {object} errors.AppError
+// @Security Bearer
+// @Router /artifacts [delete]
+//
+// Versions default to being deleted together here: the library row IS the file,
+// with a version count rather than a row per regeneration, so deleting one
+// version would leave the entry in place showing the previous one.
+func (h *Handler) DeleteLibraryArtifact(c *gin.Context) {
+ index, err := strconv.Atoi(c.Query("index"))
+ if err != nil || index < 0 {
+ _ = c.Error(errors.NewBadRequestError("invalid artifact index"))
+ return
+ }
+ h.deleteArtifact(c, &types.ArtifactDeleteRequest{
+ SessionID: secutils.SanitizeForLog(c.Query("session_id")),
+ MessageID: secutils.SanitizeForLog(c.Query("message_id")),
+ Index: index,
+ AllVersions: artifactAllVersions(c, true),
+ })
+}
+
+// artifactAllVersions reads the all_versions flag. The two routes differ only
+// in what an absent flag means, so they share one parser: an explicit value is
+// read the same way on both, and "1"/"TRUE"/"yes" cannot mean one thing here
+// and another there.
+func artifactAllVersions(c *gin.Context, whenAbsent bool) bool {
+ raw := strings.TrimSpace(c.Query("all_versions"))
+ if raw == "" {
+ return whenAbsent
+ }
+ parsed, err := strconv.ParseBool(raw)
+ if err != nil {
+ return whenAbsent
+ }
+ return parsed
+}
+
+// deleteArtifact runs the tombstone-then-reclaim sequence both delete routes
+// share. The order matters: the rows are marked first, and only the rows this
+// call actually claimed have their bytes reclaimed, so two concurrent deletes
+// cannot both try to remove the same object.
+func (h *Handler) deleteArtifact(c *gin.Context, req *types.ArtifactDeleteRequest) {
+ ctx := c.Request.Context()
+
+ result, err := h.messageService.DeleteSessionArtifact(ctx, req)
+ if err != nil {
+ // A session the caller does not own reads as absent, matching the rest
+ // of the session routes.
+ if stderrors.Is(err, errors.ErrSessionNotFound) {
+ _ = c.Error(errors.NewNotFoundError(err.Error()))
+ return
+ }
+ var appErr *errors.AppError
+ if stderrors.As(err, &appErr) {
+ _ = c.Error(appErr)
+ return
+ }
+ logger.Errorf(ctx, "delete artifact failed: session=%s message=%s idx=%d err=%v",
+ req.SessionID, req.MessageID, req.Index, err)
+ _ = c.Error(errors.NewInternalServerError(err.Error()))
+ return
+ }
+
+ // The rows are gone from every listing at this point. Reclaiming the bytes
+ // is best-effort cleanup, not part of the user-visible outcome, so its
+ // failures are logged rather than turned into a failed delete.
+ h.reclaimArtifactBlobs(ctx, types.MustTenantIDFromContext(ctx), result.Reclaim)
+
+ c.JSON(http.StatusOK, gin.H{
+ "success": true,
+ "data": gin.H{
+ "file_name": result.FileName,
+ "deleted": result.Deleted,
+ },
+ })
+}
diff --git a/internal/handler/session/artifact_delete_test.go b/internal/handler/session/artifact_delete_test.go
new file mode 100644
index 000000000..712f2a388
--- /dev/null
+++ b/internal/handler/session/artifact_delete_test.go
@@ -0,0 +1,306 @@
+package session
+
+import (
+ "context"
+ stderrors "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/Tencent/WeKnora/internal/application/service"
+ apperrors "github.com/Tencent/WeKnora/internal/errors"
+ "github.com/Tencent/WeKnora/internal/middleware"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+ "github.com/gin-gonic/gin"
+)
+
+type stubMessageServiceForDelete struct {
+ interfaces.MessageService
+ got *types.ArtifactDeleteRequest
+ result *types.ArtifactDeleteResult
+ err error
+}
+
+func (s *stubMessageServiceForDelete) DeleteSessionArtifact(
+ _ context.Context, req *types.ArtifactDeleteRequest,
+) (*types.ArtifactDeleteResult, error) {
+ s.got = req
+ return s.result, s.err
+}
+
+type deleteCatalogStub struct {
+ interfaces.ResourceCatalog
+ remaining int64
+ releaseErr error
+ released []string
+ resource *types.StoredResource
+}
+
+func (s *deleteCatalogStub) Release(_ context.Context, ref, ownerType, ownerID string) (int64, error) {
+ s.released = append(s.released, ref+"|"+ownerType+"|"+ownerID)
+ return s.remaining, s.releaseErr
+}
+
+func (s *deleteCatalogStub) ResolvePath(_ context.Context, ref string) (string, *types.StoredResource, error) {
+ if s.resource == nil {
+ return ref, nil, nil
+ }
+ return s.resource.PhysicalPath, s.resource, nil
+}
+
+type deletingFileService struct {
+ interfaces.FileService
+ deleted []string
+}
+
+func (f *deletingFileService) DeleteFile(_ context.Context, path string) error {
+ f.deleted = append(f.deleted, path)
+ return nil
+}
+
+func newArtifactDeleteRouter(h *Handler) *gin.Engine {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.Use(middleware.ErrorHandler(), func(c *gin.Context) {
+ c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), types.TenantIDContextKey, uint64(42)))
+ c.Next()
+ })
+ r.DELETE("/sessions/:id/messages/:message_id/artifacts/:index", h.DeleteMessageArtifact)
+ r.DELETE("/artifacts", h.DeleteLibraryArtifact)
+ return r
+}
+
+func TestDeleteMessageArtifactReclaimsTheBlob(t *testing.T) {
+ catalog := &deleteCatalogStub{
+ remaining: 0,
+ resource: &types.StoredResource{TenantID: 42, PhysicalPath: "local://42/exports/report.pptx"},
+ }
+ files := &deletingFileService{}
+ svc := &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
+ FileName: "报告.pptx",
+ Deleted: 1,
+ Reclaim: []types.ArtifactBlobRef{{URL: "resource://abc", MessageIDs: []string{"msg-1"}}},
+ }}
+ h := &Handler{messageService: svc, resourceCatalog: catalog, fileService: files}
+
+ w := httptest.NewRecorder()
+ newArtifactDeleteRouter(h).ServeHTTP(w,
+ httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/2", nil))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
+ }
+ if svc.got.SessionID != "sess-1" || svc.got.MessageID != "msg-1" || svc.got.Index != 2 {
+ t.Fatalf("service got %+v, want sess-1/msg-1/2", svc.got)
+ }
+ if svc.got.AllVersions {
+ t.Fatal("the in-chat panel lists versions separately, so all_versions defaults to false")
+ }
+ want := "resource://abc|" + types.ResourceOwnerMessage + "|msg-1"
+ if len(catalog.released) != 1 || catalog.released[0] != want {
+ t.Fatalf("released = %v, want [%s]", catalog.released, want)
+ }
+ // DeleteFile takes the stored reference; the catalog-backed service
+ // resolves it and marks the resource deleted itself.
+ if len(files.deleted) != 1 || files.deleted[0] != "resource://abc" {
+ t.Fatalf("deleted = %v, want [resource://abc]", files.deleted)
+ }
+}
+
+// A blob another owner still claims — an answer saved into a knowledge base, a
+// later turn that re-attached the same file — must survive the delete.
+func TestDeleteMessageArtifactKeepsBlobStillReferenced(t *testing.T) {
+ catalog := &deleteCatalogStub{remaining: 1}
+ files := &deletingFileService{}
+ h := &Handler{
+ messageService: &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
+ FileName: "shared.pptx",
+ Deleted: 1,
+ Reclaim: []types.ArtifactBlobRef{{URL: "resource://shared", MessageIDs: []string{"msg-1"}}},
+ }},
+ resourceCatalog: catalog,
+ fileService: files,
+ }
+
+ w := httptest.NewRecorder()
+ newArtifactDeleteRouter(h).ServeHTTP(w,
+ httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/0", nil))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ if len(files.deleted) != 0 {
+ t.Fatalf("deleted = %v, want none: another owner still references the blob", files.deleted)
+ }
+}
+
+// An unreadable binding count keeps the bytes: an orphaned blob is reclaimable
+// later, a file that vanished from someone else's document is not.
+func TestDeleteMessageArtifactKeepsBlobWhenReleaseFails(t *testing.T) {
+ files := &deletingFileService{}
+ h := &Handler{
+ messageService: &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
+ Deleted: 1,
+ Reclaim: []types.ArtifactBlobRef{{URL: "resource://x", MessageIDs: []string{"msg-1"}}},
+ }},
+ resourceCatalog: &deleteCatalogStub{releaseErr: stderrors.New("catalog down")},
+ fileService: files,
+ }
+
+ w := httptest.NewRecorder()
+ newArtifactDeleteRouter(h).ServeHTTP(w,
+ httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/0", nil))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: the rows are already tombstoned", w.Code)
+ }
+ if len(files.deleted) != 0 {
+ t.Fatalf("deleted = %v, want none", files.deleted)
+ }
+}
+
+// Deleting several versions can retire more than one claim on the same object:
+// a later answer that re-attached an earlier file has its own binding. Every
+// claim has to go before the bytes count as unreferenced.
+func TestDeleteArtifactReleasesEveryOwningMessage(t *testing.T) {
+ catalog := &deleteCatalogStub{remaining: 0}
+ files := &deletingFileService{}
+ h := &Handler{
+ messageService: &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{
+ FileName: "report.pptx",
+ Deleted: 2,
+ Reclaim: []types.ArtifactBlobRef{
+ {URL: "resource://abc", MessageIDs: []string{"msg-1", "msg-2"}},
+ },
+ }},
+ resourceCatalog: catalog,
+ fileService: files,
+ }
+
+ w := httptest.NewRecorder()
+ newArtifactDeleteRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
+ "/artifacts?session_id=sess-1&message_id=msg-1&index=0", nil))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
+ }
+ want := []string{
+ "resource://abc|" + types.ResourceOwnerMessage + "|msg-1",
+ "resource://abc|" + types.ResourceOwnerMessage + "|msg-2",
+ }
+ if len(catalog.released) != 2 || catalog.released[0] != want[0] || catalog.released[1] != want[1] {
+ t.Fatalf("released = %v, want %v", catalog.released, want)
+ }
+ if len(files.deleted) != 1 {
+ t.Fatalf("deleted = %v, want the object removed exactly once", files.deleted)
+ }
+}
+
+// The library row is a file with a version count, not one row per
+// regeneration, so its delete takes every version unless told otherwise.
+func TestDeleteLibraryArtifactDefaultsToAllVersions(t *testing.T) {
+ svc := &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{FileName: "a.pptx", Deleted: 3}}
+ h := &Handler{messageService: svc, fileService: &deletingFileService{}}
+ router := newArtifactDeleteRouter(h)
+
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
+ "/artifacts?session_id=sess-1&message_id=msg-1&index=0", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body=%s)", w.Code, w.Body.String())
+ }
+ if !svc.got.AllVersions {
+ t.Fatal("library deletes take every version by default")
+ }
+
+ w = httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
+ "/artifacts?session_id=sess-1&message_id=msg-1&index=0&all_versions=false", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ if svc.got.AllVersions {
+ t.Fatal("all_versions=false must be honoured")
+ }
+}
+
+// The two routes differ only in what an absent flag means. An explicit value
+// must be read identically on both, so a client cannot have "1" mean one thing
+// on one route and another elsewhere.
+func TestAllVersionsIsParsedTheSameOnBothRoutes(t *testing.T) {
+ cases := []struct {
+ query string
+ session bool // in-chat route, absent => false
+ library bool // library route, absent => true
+ }{
+ {"", false, true},
+ {"&all_versions=true", true, true},
+ {"&all_versions=false", false, false},
+ {"&all_versions=1", true, true},
+ {"&all_versions=0", false, false},
+ {"&all_versions=TRUE", true, true},
+ {"&all_versions=F", false, false},
+ // Unparseable falls back to the route's default rather than to false.
+ {"&all_versions=perhaps", false, true},
+ }
+ for _, tc := range cases {
+ t.Run("q="+tc.query, func(t *testing.T) {
+ svc := &stubMessageServiceForDelete{result: &types.ArtifactDeleteResult{Deleted: 1}}
+ router := newArtifactDeleteRouter(&Handler{messageService: svc, fileService: &deletingFileService{}})
+
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
+ "/sessions/sess-1/messages/msg-1/artifacts/0?x=1"+tc.query, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("session route status = %d, want 200", w.Code)
+ }
+ if svc.got.AllVersions != tc.session {
+ t.Fatalf("session route all_versions = %v, want %v", svc.got.AllVersions, tc.session)
+ }
+
+ w = httptest.NewRecorder()
+ router.ServeHTTP(w, httptest.NewRequest(http.MethodDelete,
+ "/artifacts?session_id=sess-1&message_id=msg-1&index=0"+tc.query, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("library route status = %d, want 200", w.Code)
+ }
+ if svc.got.AllVersions != tc.library {
+ t.Fatalf("library route all_versions = %v, want %v", svc.got.AllVersions, tc.library)
+ }
+ })
+ }
+}
+
+func TestDeleteArtifactErrorMapping(t *testing.T) {
+ cases := []struct {
+ name string
+ err error
+ want int
+ }{
+ {"already deleted or unknown", service.ErrArtifactNotFound, http.StatusNotFound},
+ {"session not owned", apperrors.ErrSessionNotFound, http.StatusNotFound},
+ {"repository failure", stderrors.New("db down"), http.StatusInternalServerError},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ h := &Handler{messageService: &stubMessageServiceForDelete{err: tc.err}}
+ w := httptest.NewRecorder()
+ newArtifactDeleteRouter(h).ServeHTTP(w,
+ httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/0", nil))
+ if w.Code != tc.want {
+ t.Fatalf("status = %d, want %d (body=%s)", w.Code, tc.want, w.Body.String())
+ }
+ })
+ }
+}
+
+func TestDeleteMessageArtifactRejectsBadIndex(t *testing.T) {
+ h := &Handler{messageService: &stubMessageServiceForDelete{}}
+ w := httptest.NewRecorder()
+ newArtifactDeleteRouter(h).ServeHTTP(w,
+ httptest.NewRequest(http.MethodDelete, "/sessions/sess-1/messages/msg-1/artifacts/-1", nil))
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", w.Code)
+ }
+}
diff --git a/internal/handler/session/artifact_download.go b/internal/handler/session/artifact_download.go
index 945060b0d..0b68c2160 100644
--- a/internal/handler/session/artifact_download.go
+++ b/internal/handler/session/artifact_download.go
@@ -9,11 +9,9 @@ import (
"strings"
"github.com/Tencent/WeKnora/internal/application/access"
- filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/filetransport"
"github.com/Tencent/WeKnora/internal/logger"
- "github.com/Tencent/WeKnora/internal/storageurl"
"github.com/Tencent/WeKnora/internal/types"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/gin-gonic/gin"
@@ -46,6 +44,10 @@ func paramSessionID(c *gin.Context) string {
// session; it does NOT return the storage URL (only names/sizes/mtimes), so
// clients cannot reach around the download endpoint by reading a
// provider:// path from the API response.
+//
+// Deleted artifacts are skipped but still consume their index: the index IS the
+// download address, so renumbering around a tombstone would point old links at
+// the wrong file.
func (h *Handler) ListSessionArtifacts(c *gin.Context) {
ctx := c.Request.Context()
sessionID := secutils.SanitizeForLog(paramSessionID(c))
@@ -74,6 +76,9 @@ func (h *Handler) ListSessionArtifacts(c *gin.Context) {
items := make([]artifactListItem, 0, len(artifacts))
for i, a := range artifacts {
+ if a.Deleted() {
+ continue
+ }
items = append(items, artifactListItem{
Index: i,
Handle: artifactHandle(a),
@@ -126,6 +131,9 @@ func (h *Handler) ListMessageArtifacts(c *gin.Context) {
items := make([]artifactListItem, 0, len(msg.Artifacts))
for i, a := range msg.Artifacts {
+ if a.Deleted() {
+ continue
+ }
items = append(items, artifactListItem{
Index: i,
Handle: artifactHandle(a),
@@ -187,6 +195,10 @@ func (h *Handler) DownloadMessageArtifact(c *gin.Context) {
return
}
artifact := msg.Artifacts[index]
+ if artifact.Deleted() {
+ _ = c.Error(errors.NewNotFoundError("artifact deleted"))
+ return
+ }
if artifact.URL == "" {
_ = c.Error(errors.NewNotFoundError("artifact storage path missing"))
return
@@ -202,36 +214,12 @@ func (h *Handler) DownloadMessageArtifact(c *gin.Context) {
_ = c.Error(errors.NewNotFoundError("artifact not accessible"))
return
}
- ctx = types.WithExecutionTenant(ctx, file.OwnerTenantID)
- fileService := h.fileService
- if h.tenantService != nil {
- tenant, lookupErr := h.tenantService.GetTenantByID(ctx, file.OwnerTenantID)
- if lookupErr != nil || tenant == nil {
- _ = c.Error(errors.NewNotFoundError("artifact workspace unavailable"))
- return
- }
- backendID, providerPath, scoped := types.ParseStorageBackendPath(file.Path)
- if !scoped {
- providerPath = file.Path
- }
- if file.StorageBackendID != "" {
- backendID = file.StorageBackendID
- }
- var ok bool
- fileService, _, ok = filesvc.ResolveTenantFileServiceWithFallback(
- ctx,
- "artifact download",
- tenant,
- backendID,
- types.ParseProviderScheme(providerPath),
- storageurl.LocalStorageBaseDir(),
- h.storageResolver,
- h.fileService,
- )
- if !ok {
- _ = c.Error(errors.NewNotFoundError("artifact storage unavailable"))
- return
- }
+ fileService, ctx, ok := h.resolveArtifactFileService(
+ ctx, file.OwnerTenantID, file.Path, file.StorageBackendID, "artifact download",
+ )
+ if !ok {
+ _ = c.Error(errors.NewNotFoundError("artifact storage unavailable"))
+ return
}
reader, err := fileService.GetFile(ctx, file.Path)
if err != nil {
diff --git a/internal/handler/session/artifact_storage.go b/internal/handler/session/artifact_storage.go
new file mode 100644
index 000000000..4bf6fdefe
--- /dev/null
+++ b/internal/handler/session/artifact_storage.go
@@ -0,0 +1,144 @@
+package session
+
+import (
+ "context"
+
+ filesvc "github.com/Tencent/WeKnora/internal/application/service/file"
+ "github.com/Tencent/WeKnora/internal/logger"
+ "github.com/Tencent/WeKnora/internal/storageurl"
+ "github.com/Tencent/WeKnora/internal/types"
+ "github.com/Tencent/WeKnora/internal/types/interfaces"
+)
+
+// resolveArtifactFileService returns the file service that owns an artifact's
+// bytes, plus a context scoped to the owning tenant.
+//
+// Artifacts are not always on the process-wide file service: a tenant can pin
+// its workspace to its own storage backend, and the object then only exists
+// there. Both reading and deleting an artifact have to go through the same
+// resolution, which is why it lives here rather than inline in the download
+// handler.
+//
+// ok is false when the owning tenant or its backend cannot be reached; callers
+// treat that as "artifact unavailable" rather than falling back to the default
+// service, which would look in the wrong bucket.
+func (h *Handler) resolveArtifactFileService(
+ ctx context.Context, ownerTenantID uint64, path, storageBackendID, label string,
+) (interfaces.FileService, context.Context, bool) {
+ ctx = types.WithExecutionTenant(ctx, ownerTenantID)
+ if h.fileService == nil {
+ return nil, ctx, false
+ }
+ if h.tenantService == nil {
+ return h.fileService, ctx, true
+ }
+ tenant, err := h.tenantService.GetTenantByID(ctx, ownerTenantID)
+ if err != nil || tenant == nil {
+ return nil, ctx, false
+ }
+ backendID, providerPath, scoped := types.ParseStorageBackendPath(path)
+ if !scoped {
+ providerPath = path
+ }
+ if storageBackendID != "" {
+ backendID = storageBackendID
+ }
+ fileService, _, ok := filesvc.ResolveTenantFileServiceWithFallback(
+ ctx,
+ label,
+ tenant,
+ backendID,
+ types.ParseProviderScheme(providerPath),
+ storageurl.LocalStorageBaseDir(),
+ h.storageResolver,
+ h.fileService,
+ )
+ if !ok {
+ return nil, ctx, false
+ }
+ return fileService, ctx, true
+}
+
+// reclaimArtifactBlobs deletes the stored objects behind artifacts that were
+// just tombstoned. Best-effort by design: the rows are already marked, and a
+// blob left behind is recoverable (the tombstone still carries its url) while a
+// failed request after a successful tombstone is not.
+//
+// A blob is only removed once the owning message's claim on it was the last
+// one. An answer saved into a knowledge base, or a later turn that re-attached
+// the same file, holds its own binding; deleting the bytes underneath it would
+// break a document nobody asked to delete.
+func (h *Handler) reclaimArtifactBlobs(ctx context.Context, tenantID uint64, refs []types.ArtifactBlobRef) {
+ for _, ref := range refs {
+ if ref.URL == "" {
+ continue
+ }
+ path, ownerTenantID, backendID, ok := h.locateArtifactBlob(ctx, tenantID, ref)
+ if !ok {
+ continue
+ }
+ fileService, blobCtx, ok := h.resolveArtifactFileService(
+ ctx, ownerTenantID, path, backendID, "artifact delete",
+ )
+ if !ok {
+ logger.Warnf(ctx, "artifact delete: storage unavailable for %s, blob kept", ref.URL)
+ continue
+ }
+ // DeleteFile takes the stored reference: the catalog-backed service
+ // resolves it and marks the resource deleted once the bytes are gone.
+ if err := fileService.DeleteFile(blobCtx, ref.URL); err != nil {
+ logger.Warnf(ctx, "artifact delete: failed to remove blob %s: %v", ref.URL, err)
+ }
+ }
+}
+
+// locateArtifactBlob drops every deleted message's claim on a blob and, when
+// nothing is left holding it, reports where the bytes live. ok is false
+// whenever the blob must be kept — another owner still references it, or a
+// release failed and we cannot tell.
+//
+// An unreadable binding count keeps the file, matching the knowledge-delete
+// path: an orphaned blob is reclaimable later, a file that vanished from
+// someone else's document is not.
+func (h *Handler) locateArtifactBlob(
+ ctx context.Context, tenantID uint64, ref types.ArtifactBlobRef,
+) (path string, ownerTenantID uint64, backendID string, ok bool) {
+ if h.resourceCatalog == nil {
+ // No catalog: the url is a provider path in the caller's own tenant and
+ // nothing else can be holding a reference to it.
+ return ref.URL, tenantID, "", true
+ }
+ // -1 means the reference is not a catalog handle, i.e. there are no claims
+ // to account for; only a non-negative count is a real answer.
+ remaining := int64(-1)
+ for _, messageID := range ref.MessageIDs {
+ count, err := h.resourceCatalog.Release(ctx, ref.URL, types.ResourceOwnerMessage, messageID)
+ if err != nil {
+ logger.Warnf(ctx, "artifact delete: failed to release %s, blob kept: %v", ref.URL, err)
+ return "", 0, "", false
+ }
+ if count >= 0 {
+ remaining = count
+ }
+ }
+ if remaining > 0 {
+ logger.Infof(ctx, "artifact delete: keeping %s, %d owner(s) still reference it", ref.URL, remaining)
+ return "", 0, "", false
+ }
+ resolved, resource, err := h.resourceCatalog.ResolvePath(ctx, ref.URL)
+ if err != nil {
+ logger.Warnf(ctx, "artifact delete: failed to resolve %s, blob kept: %v", ref.URL, err)
+ return "", 0, "", false
+ }
+ if resource == nil {
+ return resolved, tenantID, "", true
+ }
+ if resource.TenantID != tenantID {
+ // The session is the caller's, so its artifacts should be too. A
+ // mismatch means the url points somewhere unexpected; leave it alone.
+ logger.Warnf(ctx, "artifact delete: %s belongs to tenant %d, not %d; blob kept",
+ ref.URL, resource.TenantID, tenantID)
+ return "", 0, "", false
+ }
+ return resolved, resource.TenantID, resource.StorageBackendID, true
+}
diff --git a/internal/router/routes_chat.go b/internal/router/routes_chat.go
index 6450a60d9..1f8bc8722 100644
--- a/internal/router/routes_chat.go
+++ b/internal/router/routes_chat.go
@@ -108,6 +108,9 @@ func RegisterSessionRoutes(
sessions.GET("/:id/artifacts", handler.ListSessionArtifacts)
sessions.GET("/:id/messages/:message_id/artifacts", handler.ListMessageArtifacts)
sessions.GET("/:id/messages/:message_id/artifacts/:index/download", handler.DownloadMessageArtifact)
+ // Deleting reclaims the stored bytes, so it is owner-only: unlike the
+ // download above it does not honour shared-agent read access.
+ sessions.DELETE("/:id/messages/:message_id/artifacts/:index", handler.DeleteMessageArtifact)
}
// Cross-session artifact library. Same guards as /sessions: the rows come
@@ -116,6 +119,10 @@ func RegisterSessionRoutes(
artifacts := g.apiKeyGroup(r.Group("/artifacts", g.Viewer()), apiKeyChat(apiKeyFullAccess()))
{
artifacts.GET("", handler.ListArtifactLibrary)
+ // The artifact to delete is addressed by query parameters rather than a
+ // path: the library row already carries session_id/message_id/index, and
+ // a path would have to repeat the /sessions tree under a second prefix.
+ artifacts.DELETE("", handler.DeleteLibraryArtifact)
}
}
diff --git a/internal/types/interfaces/message.go b/internal/types/interfaces/message.go
index ad1f28800..31159fc3e 100644
--- a/internal/types/interfaces/message.go
+++ b/internal/types/interfaces/message.go
@@ -68,6 +68,14 @@ type MessageService interface {
// 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)
+
+ // DeleteSessionArtifact tombstones a skill-generated file (and optionally
+ // every version of it) in a session the caller owns, and reports the blobs
+ // whose bytes the caller should now reclaim. Shared-agent read access does
+ // not carry delete rights.
+ DeleteSessionArtifact(
+ ctx context.Context, req *types.ArtifactDeleteRequest,
+ ) (*types.ArtifactDeleteResult, error)
}
// MessageRepository defines the message repository interface
@@ -153,6 +161,28 @@ type MessageRepository interface {
ListArtifactLibrary(
ctx context.Context, query *types.ArtifactLibraryQuery,
) ([]*types.ArtifactLibraryItem, int64, error)
+ // FindSessionArtifact returns the live artifact row addressed by
+ // (session, message, position), or nil when there is none. A tombstoned
+ // row reads as absent.
+ FindSessionArtifact(
+ ctx context.Context, sessionID, messageID string, position int,
+ ) (*types.MessageArtifactRecord, error)
+ // FindSessionArtifactVersions returns every live row of the session sharing
+ // sourcePath — the regenerations the artifact library folds into one entry.
+ // An empty sourcePath yields nothing: such artifacts have no version group.
+ FindSessionArtifactVersions(
+ ctx context.Context, sessionID, sourcePath string,
+ ) ([]types.MessageArtifactRecord, error)
+ // SoftDeleteSessionArtifacts tombstones the referenced rows and returns the
+ // subset it marked, leaving out rows another caller already tombstoned.
+ SoftDeleteSessionArtifacts(
+ ctx context.Context, sessionID string, refs []types.ArtifactRef, at time.Time,
+ ) ([]types.ArtifactRef, error)
+ // CountLiveArtifactsByURL counts undeleted artifact rows pointing at a
+ // stored object, across every session. Callers use it as the last guard
+ // before reclaiming bytes that a fork copy, a legacy raw path or a later
+ // re-attachment may still need.
+ CountLiveArtifactsByURL(ctx context.Context, url string) (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.go
index 36e8fbced..28d5c1610 100644
--- a/internal/types/message.go
+++ b/internal/types/message.go
@@ -240,11 +240,35 @@ type MessageArtifact struct {
SourcePath string `json:"source_path"` // Absolute path inside the sandbox (used for diff)
ModTime time.Time `json:"mod_time"` // Sandbox-side modification time (used for diff)
CreatedAt time.Time `json:"created_at"` // When WeKnora persisted the blob
+ // DeletedAt marks a file the user deleted. The entry stays in the list
+ // rather than being removed because its position IS the download address
+ // (msg.Artifacts[index]); dropping it would shift every later file's index
+ // and hand an old link the wrong blob. Keeping it also keeps the entry in
+ // ArtifactCollector's de-duplication set, so the next collect does not
+ // re-attach the very file that was deleted — its sandbox mtime has not
+ // moved. Clients filter these out; the bytes are already reclaimed.
+ DeletedAt *time.Time `json:"deleted_at,omitempty"`
}
+// Deleted reports whether the user deleted this artifact.
+func (a MessageArtifact) Deleted() bool { return a.DeletedAt != nil }
+
// MessageArtifacts is a slice of MessageArtifact for database storage.
type MessageArtifacts []MessageArtifact
+// Live returns the artifacts the user has not deleted, preserving order. The
+// caller loses the positional index, so use it for counting and display only —
+// anything that addresses an artifact for download must index the full slice.
+func (m MessageArtifacts) Live() MessageArtifacts {
+ out := make(MessageArtifacts, 0, len(m))
+ for _, a := range m {
+ if !a.Deleted() {
+ out = append(out, a)
+ }
+ }
+ return out
+}
+
// Value implements the driver.Valuer interface for database serialization
func (m MessageArtifacts) Value() (driver.Value, error) {
if m == nil {
diff --git a/internal/types/message_artifact.go b/internal/types/message_artifact.go
index 7e68b8009..d4a1f01d1 100644
--- a/internal/types/message_artifact.go
+++ b/internal/types/message_artifact.go
@@ -25,6 +25,12 @@ type MessageArtifactRecord struct {
// PostgreSQL timestamps would truncate to microseconds. Empty means zero.
ModTime string `gorm:"column:mod_time"`
CreatedAt time.Time `gorm:"column:created_at"`
+ // DeletedAt is set when the user deleted the file. The row is a tombstone
+ // from then on: it holds position (the download address) and keeps the
+ // collector from re-attaching the sandbox file, while the blob itself has
+ // been reclaimed. URL is left in place so a later GC can retry a reclaim
+ // that failed.
+ DeletedAt *time.Time `gorm:"column:deleted_at"`
}
// TableName implements gorm's tabler.
@@ -60,6 +66,7 @@ func NewMessageArtifactRecords(sessionID, messageID string, list MessageArtifact
SourcePath: a.SourcePath,
ModTime: FormatArtifactModTime(a.ModTime),
CreatedAt: created,
+ DeletedAt: a.DeletedAt,
})
}
return rows
@@ -97,6 +104,7 @@ func (r MessageArtifactRecord) Artifact() MessageArtifact {
SourcePath: r.SourcePath,
ModTime: ParseArtifactModTime(r.ModTime),
CreatedAt: r.CreatedAt,
+ DeletedAt: r.DeletedAt,
}
}
@@ -130,3 +138,51 @@ type ArtifactLibraryItem struct {
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
VersionCount int `json:"version_count" gorm:"column:version_count"`
}
+
+// ArtifactRef addresses one artifact row by its business key. The primary key
+// is not usable for this: writeMessageArtifacts rewrites a message's rows with
+// fresh UUIDs whenever the message is updated, while (message, position) is
+// stable for the life of the artifact.
+type ArtifactRef struct {
+ MessageID string
+ Position int
+}
+
+// ArtifactDeleteRequest addresses the artifact a user asked to delete.
+// SessionID/MessageID/Index are the same coordinates the download endpoint
+// takes, so a client deletes exactly what it was showing.
+type ArtifactDeleteRequest struct {
+ SessionID string
+ MessageID string
+ Index int
+ // AllVersions extends the delete to every regeneration of the same sandbox
+ // file in this session. The artifact library shows one row per file with a
+ // version count, so deleting from there sets this; the in-chat panel lists
+ // each version separately and leaves it false.
+ AllVersions bool
+}
+
+// ArtifactBlobRef is one stored object the delete orphaned. The caller resolves
+// the owning tenant's file service and releases the resource binding before
+// removing the bytes, so a blob another message or knowledge entry still claims
+// survives.
+//
+// MessageIDs is every deleted message that owned this object: a later answer
+// that re-attaches an earlier file stores its own row and its own binding, so
+// one delete can retire several claims on the same bytes and all of them have
+// to be released before the object counts as unreferenced.
+type ArtifactBlobRef struct {
+ URL string
+ MessageIDs []string
+}
+
+// ArtifactDeleteResult reports what a delete tombstoned.
+type ArtifactDeleteResult struct {
+ // FileName of the artifact the request addressed, for the response body.
+ FileName string
+ // Deleted counts the rows this call tombstoned. Zero means another caller
+ // got there first; the blobs are then theirs to reclaim, not ours.
+ Deleted int
+ // Reclaim lists the distinct blobs whose bytes may now be removed.
+ Reclaim []ArtifactBlobRef
+}
diff --git a/migrations/sqlite/000026_message_artifacts_deleted_at.down.sql b/migrations/sqlite/000026_message_artifacts_deleted_at.down.sql
new file mode 100644
index 000000000..7b98ad730
--- /dev/null
+++ b/migrations/sqlite/000026_message_artifacts_deleted_at.down.sql
@@ -0,0 +1,4 @@
+DROP INDEX IF EXISTS idx_message_artifacts_url_live;
+DROP INDEX IF EXISTS idx_message_artifacts_session_live;
+
+ALTER TABLE message_artifacts DROP COLUMN deleted_at;
diff --git a/migrations/sqlite/000026_message_artifacts_deleted_at.up.sql b/migrations/sqlite/000026_message_artifacts_deleted_at.up.sql
new file mode 100644
index 000000000..630ee39a0
--- /dev/null
+++ b/migrations/sqlite/000026_message_artifacts_deleted_at.up.sql
@@ -0,0 +1,12 @@
+-- Mirrors versioned migration 000107_message_artifacts_deleted_at: user-deleted
+-- artifacts become tombstones so positions stay stable and the collector does
+-- not re-attach them from the sandbox.
+ALTER TABLE message_artifacts ADD COLUMN deleted_at DATETIME;
+
+CREATE INDEX IF NOT EXISTS idx_message_artifacts_session_live
+ ON message_artifacts (session_id, created_at)
+ WHERE deleted_at IS NULL;
+
+CREATE INDEX IF NOT EXISTS idx_message_artifacts_url_live
+ ON message_artifacts (url)
+ WHERE deleted_at IS NULL;
diff --git a/migrations/versioned/000107_message_artifacts_deleted_at.down.sql b/migrations/versioned/000107_message_artifacts_deleted_at.down.sql
new file mode 100644
index 000000000..bd48585c7
--- /dev/null
+++ b/migrations/versioned/000107_message_artifacts_deleted_at.down.sql
@@ -0,0 +1,7 @@
+-- Reverting drops the tombstone marker, which resurrects every deleted file in
+-- the listings. The blobs of hard-deleted artifacts are already gone, so those
+-- rows will 404 on download until they are cleaned up.
+DROP INDEX IF EXISTS idx_message_artifacts_url_live;
+DROP INDEX IF EXISTS idx_message_artifacts_session_live;
+
+ALTER TABLE message_artifacts DROP COLUMN IF EXISTS deleted_at;
diff --git a/migrations/versioned/000107_message_artifacts_deleted_at.up.sql b/migrations/versioned/000107_message_artifacts_deleted_at.up.sql
new file mode 100644
index 000000000..1e2f4dd25
--- /dev/null
+++ b/migrations/versioned/000107_message_artifacts_deleted_at.up.sql
@@ -0,0 +1,32 @@
+-- Migration: 000107_message_artifacts_deleted_at
+-- Users can now delete a generated file from the artifact library or the
+-- in-chat artifact panel. The row is kept as a tombstone rather than removed:
+--
+-- * message_artifacts.position is the address the download endpoint uses
+-- (msg.Artifacts[index]); physically removing a middle row would shift
+-- every later file's index and hand old links the wrong blob.
+-- * ArtifactCollector de-duplicates sandbox files against the rows of the
+-- session. Dropping the row would let the next collect re-attach the very
+-- file the user just deleted, because its sandbox mtime has not moved.
+--
+-- The blob itself IS reclaimed (once no other owner still binds the resource),
+-- so url stays on the tombstone only as a handle for a later GC retry.
+DO $$ BEGIN RAISE NOTICE '[Migration 000107] Adding message_artifacts.deleted_at'; END $$;
+
+ALTER TABLE message_artifacts
+ ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMP WITH TIME ZONE;
+
+-- The artifact library and both list endpoints read live rows only; the
+-- partial index keeps those scans off the tombstones.
+CREATE INDEX IF NOT EXISTS idx_message_artifacts_session_live
+ ON message_artifacts (session_id, created_at)
+ WHERE deleted_at IS NULL;
+
+-- Before a delete reclaims an object's bytes it checks whether any live row
+-- anywhere still points at the same url (a forked session's copied rows, a
+-- later answer that re-attached the file). That lookup is by url alone.
+CREATE INDEX IF NOT EXISTS idx_message_artifacts_url_live
+ ON message_artifacts (url)
+ WHERE deleted_at IS NULL;
+
+COMMENT ON COLUMN message_artifacts.deleted_at IS 'Set when the user deleted the file; the row survives to keep position stable and to stop the collector re-attaching it';
diff --git a/website-docs/03-features/18-chat-experience.md b/website-docs/03-features/18-chat-experience.md
index 0499fbf15..087f66d2a 100644
--- a/website-docs/03-features/18-chat-experience.md
+++ b/website-docs/03-features/18-chat-experience.md
@@ -31,7 +31,9 @@
需要让智能体生成可下载文件时,产物应保存到 `/workspace/output`,系统会在回答结束时收集并持久化。上传的附件暂存于 `/workspace/input`,脚本和中间文件可放在 `/workspace` 的其他目录。输入附件和输出文件分别管理,删除输入附件不会自动删除已收集的输出文件。
-文件读取、脚本执行和目录约定见[技能与沙箱](22-skills-sandbox.md);列表与下载接口见[会话与聊天 API](../04-api/02-api-chat.md)。
+不再需要的文件可以在会话文件面板或「产物」页删除。删除会回收存储中的字节,无法恢复,因此会先确认;只有会话归属人能删除,通过共享智能体获得的只读访问只能下载。会话文件面板按每次生成分别列出,删除的是点击的那一版;「产物」页一行代表一个文件(带版本数),删除会连同该文件在这个会话中的所有历史版本。同一份文件如果已被存入知识库或被后续回答重新引用,那些位置不受影响。删除后沙箱里的同名文件也不会被重新收录。
+
+文件读取、脚本执行和目录约定见[技能与沙箱](22-skills-sandbox.md);列表、下载与删除接口见[会话与聊天 API](../04-api/02-api-chat.md)。
## 回顾和导出对话
diff --git a/website-docs/04-api/02-api-chat.md b/website-docs/04-api/02-api-chat.md
index 16c539acf..03cb0bd87 100644
--- a/website-docs/04-api/02-api-chat.md
+++ b/website-docs/04-api/02-api-chat.md
@@ -375,6 +375,7 @@ curl -X DELETE $BASE/api/v1/messages/s-1/m-1 -H "Authorization: Bearer $TOKEN"
| GET | `/api/v1/sessions/:id/artifacts` | 200 `{success:true,data:[Artifact]}`,汇总会话文件 |
| GET | `/api/v1/sessions/:id/messages/:message_id/artifacts` | 同上,仅本条消息文件 |
| GET | `/api/v1/sessions/:id/messages/:message_id/artifacts/:index/download` | 200 文件流,Content-Disposition: attachment |
+| DELETE | `/api/v1/sessions/:id/messages/:message_id/artifacts/:index` | 200 `{success:true,data:{file_name,deleted}}`,删除该文件 |
Artifact 字段:index、handle(可选 resource:// 引用)、file_name、file_type、file_size、source_path、mod_time、created_at。响应不返回底层对象存储 URL。下载 index 从 0 开始,必须使用对应消息列表的索引,不能拿会话汇总索引直接拼消息下载地址。非法索引返回 400,越界或文件不存在返回 404。
@@ -385,6 +386,25 @@ curl "$BASE/api/v1/sessions/session-1/messages/message-1/artifacts/0/download" \
-H "Authorization: Bearer $TOKEN" -o result.pdf
```
+### 删除生成的文件
+
+删除会回收对象存储中的字节,**不可恢复**。与下载不同,删除只对会话归属人开放:通过共享智能体获得的只读访问可以下载文件,但不能删除 —— 不属于自己的会话一律按 404 处理(不区分「不存在」和「无权限」,与其余会话接口一致)。已删除的文件返回 404,重复删除同样返回 404。
+
+字节只有在没有任何其他持有者时才会真正回收:同一份文件被存入知识库、被后续回答重新引用,或者所在会话被分叉出副本,都会让它保留下来。回收失败不影响删除结果(接口仍返回 200),文件在各处列表中都已消失。
+
+删除后该文件在列表接口和产物库中都不再出现,但它在消息中的**位置会被保留**:`index` 就是下载地址,如果后面的文件依次前移,已有的下载链接就会指向错的文件。同一原因,沙箱里的同名文件不会在下一轮采集时被重新收录 —— 它的 mtime 并没有因为用户删除而改变。
+
+只有当没有其他持有者仍然引用该对象时才会真正删除字节:同一份文件如果被存入知识库、或被后续回答重新引用,都会各自持有一份引用,删除其中一处不会动到底层数据。
+
+| 参数 | 说明 |
+| --- | --- |
+| `all_versions` | 连同本会话中同一 `source_path` 的所有历史版本一并删除。布尔值,默认 `false` |
+
+```bash
+curl -X DELETE "$BASE/api/v1/sessions/session-1/messages/message-1/artifacts/0" \
+ -H "Authorization: Bearer $TOKEN"
+```
+
### 跨会话产物列表
`GET /api/v1/artifacts` 列出当前用户网页对话中的所有生成文件,供首页侧栏「产物」页使用。范围与会话列表的 `source=web` 一致:本人会话及历史上无归属的租户级网页会话;IM 渠道、网页挂件(embed)和 API Key 会话一律不含,即使 IM 会话在库中没有归属人。同一会话中 `source_path` 相同的文件视为同一文件的多个版本,只返回最新一版,`version_count` 给出版本数。已删除的会话或消息中的文件不返回。权限要求与上表相同。
@@ -402,6 +422,13 @@ curl "$BASE/api/v1/artifacts?file_types=.pptx,.pdf&keyword=报告&page=1&page_si
-H "Authorization: Bearer $TOKEN"
```
+`DELETE /api/v1/artifacts` 删除产物库中的一个文件,用 query 参数 `session_id`、`message_id`、`index` 定位,语义与上面的会话内删除一致。区别只在于 `all_versions` 缺省时视为 `true`(显式传值时两个接口的解析规则相同):产物库一行代表一个文件(`version_count` 给出版本数)而不是某一次生成,只删最新一版会让这一行继续留在列表里、显示上一版。传 `all_versions=false` 可只删当前这一版。
+
+```bash
+curl -X DELETE "$BASE/api/v1/artifacts?session_id=session-1&message_id=message-1&index=0" \
+ -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)。