From 9e0c28fbc93f4b3abf982a0050a1cd5372cba72a Mon Sep 17 00:00:00 2001 From: lyingbug Date: Sun, 20 Sep 2026 13:01:46 +0800 Subject: [PATCH] feat(artifacts): let users delete generated files (#3447) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(artifacts): let users delete generated files 技能生成的文件此前只能列出、预览和下载,没有任何删除入口,后端 handler/service/repository 三层都没有实现。DeleteSession 里那句注释 ("a dedicated GC job or explicit hard-delete API is the right place to reclaim storage") 留的就是这个位置。 Tombstone, not a row delete. message_artifacts 新增 deleted_at,删除只 打标记不删行。position 是下载接口寻址用的下标(msg.Artifacts[index]), 物理删掉中间一行会让它后面的文件整体前移,已有链接下到错的文件;而 ArtifactCollector 的去重集就是从这张表读的,行没了之后沙箱里 mtime 未变 的同名文件下一轮就会被重新采集回来,删了又出现。墓碑同时挡住这两条。 loadArtifactsByMessage 因此刻意保留墓碑,展示侧用 MessageArtifacts.Live 过滤;NewMessageArtifactRecords 带上 DeletedAt,任何一次消息重写都能把 墓碑原样写回去。 Bytes. 字节是真回收的,走 catalog.Release 引用计数:一份文件可能同时被 知识库条目和后续回答持有,只有所有持有者都放手才 DeleteFile。删多个版本 时同一个对象可能来自多条消息,每条消息的绑定都要释放,字节只删一次。 回收发生在打标记之后,且只针对本次调用真正认领到的行——并发的第二次删除 认领不到任何行,也就不会去动别人正在回收的对象。释放失败一律保留字节: 留个孤儿 blob 以后还能靠墓碑上的 url 回收,删错了则是别人的文档里的图片 凭空消失。 Scope. 会话内面板每个版本单独一行,删的就是点的那一版;产物库一行代表 一个文件(带版本数),默认连同该文件在这个会话里的所有版本一起删,否则 删完这一行还在、只是显示上一版。权限比下载严一档:下载认共享智能体的 只读访问,删除只认会话归属人。 Inline references. 正文里的 resource:// 引用渲染成置灰加删除线的卡片, 不可点击,和「模型引用了不存在的文件」的 --pending 态区分开。图片类产物 也降级成卡片:走 renderImage 只会拉取失败,留下一张永远加载不出来的图。 墓碑必须留在传给渲染器的产物列表里——句柄形式与知识库图片同形,过滤掉 之后句柄对不上本条回答,会被当成外部受保护图片去拉一个已经不存在的 blob,结果是裂图。组件里因此拆出 liveArtifacts 只给计数和文件列表用。 Also: 产物库是 offset 分页的无限列表,删一行会让后续页整体前移漏掉一条, 改成按已显示行数取下一页并按 key 去重;access.ResolveMessageArtifact 与 MessageReferencesFile 不再让墓碑授权访问;SessionArtifacts 过滤墓碑, 避免新回答把引用绑到已删文件上;版本澄清文案不再把已删版本算进版本数。 docs/swagger.* 未重新生成:仓库里那份已经落后若干功能,重生成会带进约 1000 行无关漂移,另开 PR 同步。 * fix(artifacts): close the delete holes found in review Regeneration. loadKnownSet 把墓碑的 ContentHash 也放进了去重集,于是 knownSameContent 会把「删除后技能重新生成、字节恰好相同」当成 fork checkout 那种 restore:不上传、不挂回本轮回答,文件再也回不来。墓碑现在 只登记 (path, mtime),不进 hash 也不进 byPath —— 前者才是「沙箱文件没动 过就别复活」需要的键,后者是「同内容恢复」的短路,两件事不该共用。 RecordRestoredArtifactMtime 也不再改墓碑:它的 mtime 就是那把锁。 Message file proxy. /sessions/:id/messages/:message_id/files 走 MessageReferencesFile,而正文检查在最前面且无条件为真。删除不会重写回答, resource:// 句柄还留在正文里,于是这条代理会继续把已删文件交出去——包括 交给共享智能体的只读访客,也包括「字节因为知识库还持有而没被回收」的情形。 现在先看 artifacts:命中本条消息的墓碑直接 false,命中 live 直接 true, 其余(知识库图、附件)才回落到正文。同一文件挂在多个位置时只要还有一个 live 就仍然可取。 Cross-session bytes. CreateForked 复制产物行时连同存储 URL 一起复制,但 不会给副本重新 Bind,所以 catalog 的引用计数看不到分叉。在父会话里删除会 把分叉还在用的字节删掉。无 catalog 部署、以及存的是裸 provider 路径的行, 同样不在计数覆盖内。回收前新增一道 CountLiveArtifactsByURL:只要还有任何 未删除的行指向同一对象就保留字节,查不出来也保留。配套加了 url 的部分索引。 Atomicity. SoftDeleteSessionArtifacts 原来逐条 UPDATE 不带事务,删多版本 时中途失败会留下「一部分已隐藏、字节没回收、接口 500、用户重试 404」。 现在整批放进一个事务。writeMessageArtifacts 是整表替换,拿着删除前快照的 并发写会让墓碑复活而字节已在回收,现在按 position 把已存在的 deleted_at 合并回去——删除是唯一不允许被过期写覆盖的属性。 all_versions 两个路由改用同一个解析器(strconv.ParseBool),此前一个是 == "true"、另一个是 != "false",显式传 1/TRUE 在两边语义不同;缺省值仍 按路由区分。 测试:收集器三条(未动不复活 / 重新生成要回来 / live 的同内容恢复仍短路)、 access 三条(正文不能复活已删授权、多副本只要有 live 就可取、非产物引用 仍走正文)、service 七条(归属人校验、他人会话拒绝、并发认领为空、live 行仍在则保留字节、guard 失败保留字节、多版本按对象归并 owner、无 source_path 不扫全会话)、repository 三条(墓碑抗过期写、事务回滚、跨会话 URL 计数)、handler 一条(两个路由的 all_versions 解析矩阵)。其中 「重新生成要回来」在改回旧实现时确认会失败。 client/ 没有 artifacts 相关 API(只有一个 SSE 事件类型常量),无需同步。 --- frontend/src/api/artifacts.ts | 24 +- frontend/src/api/chat/index.ts | 24 ++ .../src/components/chat/SandboxSidePanel.vue | 5 + .../src/components/css/chat-markdown.less | 22 ++ frontend/src/i18n/embed.ts | 9 +- frontend/src/i18n/locales/en-US.ts | 12 + frontend/src/i18n/locales/ja-JP.ts | 12 + frontend/src/i18n/locales/ko-KR.ts | 12 + frontend/src/i18n/locales/ru-RU.ts | 12 + frontend/src/i18n/locales/zh-CN.ts | 12 + .../src/utils/sandboxArtifactRefs.test.ts | 45 ++- frontend/src/utils/sandboxArtifactRefs.ts | 48 ++- frontend/src/utils/sessionArtifacts.test.ts | 43 +++ frontend/src/utils/sessionArtifacts.ts | 31 ++ .../src/views/artifacts/ArtifactLibrary.vue | 96 ++++- .../chat/components/AgentStreamDisplay.vue | 12 +- .../chat/components/ChatArtifactsPanel.vue | 78 +++- frontend/src/views/chat/components/botmsg.vue | 12 +- frontend/src/views/chat/index.vue | 10 +- internal/application/access/files.go | 51 ++- internal/application/access/files_test.go | 64 ++++ .../repository/message_artifact.go | 185 +++++++++- .../message_artifact_delete_test.go | 342 ++++++++++++++++++ .../application/service/artifact_collector.go | 30 +- .../service/artifact_collector_test.go | 123 +++++++ .../service/message_artifact_delete.go | 178 +++++++++ .../service/message_artifact_delete_test.go | 201 ++++++++++ .../service/message_artifact_versions.go | 14 +- .../migration_sqlite_versioned_schema_test.go | 3 +- internal/handler/session/artifact_delete.go | 135 +++++++ .../handler/session/artifact_delete_test.go | 306 ++++++++++++++++ internal/handler/session/artifact_download.go | 52 +-- internal/handler/session/artifact_storage.go | 144 ++++++++ internal/router/routes_chat.go | 7 + internal/types/interfaces/message.go | 30 ++ internal/types/message.go | 24 ++ internal/types/message_artifact.go | 56 +++ ...0026_message_artifacts_deleted_at.down.sql | 4 + ...000026_message_artifacts_deleted_at.up.sql | 12 + ...0107_message_artifacts_deleted_at.down.sql | 7 + ...000107_message_artifacts_deleted_at.up.sql | 32 ++ .../03-features/18-chat-experience.md | 4 +- website-docs/04-api/02-api-chat.md | 27 ++ 43 files changed, 2478 insertions(+), 72 deletions(-) create mode 100644 internal/application/repository/message_artifact_delete_test.go create mode 100644 internal/application/service/message_artifact_delete.go create mode 100644 internal/application/service/message_artifact_delete_test.go create mode 100644 internal/handler/session/artifact_delete.go create mode 100644 internal/handler/session/artifact_delete_test.go create mode 100644 internal/handler/session/artifact_storage.go create mode 100644 migrations/sqlite/000026_message_artifacts_deleted_at.down.sql create mode 100644 migrations/sqlite/000026_message_artifacts_deleted_at.up.sql create mode 100644 migrations/versioned/000107_message_artifacts_deleted_at.down.sql create mode 100644 migrations/versioned/000107_message_artifacts_deleted_at.up.sql diff --git a/frontend/src/api/artifacts.ts b/frontend/src/api/artifacts.ts index c4e50271..2aa14caf 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('/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(`/api/v1/artifacts?${query.toString()}`) +} diff --git a/frontend/src/api/chat/index.ts b/frontend/src/api/chat/index.ts index 31322c43..e74c199f 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 1a168aed..692c2076 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)" /> @@ -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 2a26df94..82a7ff88 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 2a96dba4..276e4222 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": "找到 {count} 个网络搜索结果", @@ -871,7 +872,8 @@ const messages = { "download": "ダウンロード", "downloadFailed": "ダウンロードに失敗しました。再試行してください。", "inlinePreviewHint": "クリックしてプレビュー", - "inlineMissing": "ファイルを利用できません" + "inlineMissing": "ファイルを利用できません", + "inlineDeleted": "ファイルは削除されました" }, "updatePlan": "計画を更新", "webSearchFound": "Web検索結果を{count}件見つけました", @@ -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 {count} web search result(s)", diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 9f6d5c1f..afa3cd03 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 {count} web search result(s)', diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index c5b3f6ee..932faed3 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検索結果を{count}件見つけました', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index 165c1f5a..7a05c85f 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: '{count}개의 웹 검색 결과 발견', @@ -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 55b9d1fe..3321ee93 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: 'Найдено {count} результатов веб‑поиска', @@ -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 82c10bc6..8d7eed33 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: '找到 {count} 个网络搜索结果', @@ -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 e3ef5b71..6d7c923a 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.']) { @@ -203,3 +203,46 @@ test('artifact names are HTML-escaped', () => { assert.ok(!html?.includes(' { + 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(' { + // 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 ee46e922..d75ac376 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 = ''; -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 会把图片包在

里,块级元素会被 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 ( `` + `` @@ -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 { diff --git a/frontend/src/utils/sessionArtifacts.test.ts b/frontend/src/utils/sessionArtifacts.test.ts index 03b6fd09..8f7eaeeb 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 f7423cb9..2542b420 100644 --- a/frontend/src/utils/sessionArtifacts.ts +++ b/frontend/src/utils/sessionArtifacts.ts @@ -19,6 +19,10 @@ function readMessageId(message: Record): 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 06601146..fe1c9e94 100644 --- a/frontend/src/views/artifacts/ArtifactLibrary.vue +++ b/frontend/src/views/artifacts/ArtifactLibrary.vue @@ -115,6 +115,18 @@ > + + + @@ -162,6 +174,18 @@ > + + + (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>({}) +const deleting = reactive>({}) const previewItem = ref(null) const previewVisible = ref(false) const previewActions = ref(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 8fac74f0..8f246422 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" /> @@ -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 cd60e8da..edf7e039 100644 --- a/frontend/src/views/chat/components/ChatArtifactsPanel.vue +++ b/frontend/src/views/chat/components/ChatArtifactsPanel.vue @@ -30,6 +30,20 @@ + + +

@@ -123,6 +137,20 @@ + + + @@ -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(null) const listRef = ref(null) const previewItem = ref(null) const downloading = reactive>({}) +const deleting = reactive>({}) const focusedMessageId = ref(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 42ddb0a2..d92a941a 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" /> @@ -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 7944c9ce..b1fb0bf7 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" />