Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(file-viewer): image viewer tools — annotate & comment into chat, remove background, erase, resize (#20376)

Arvin Xu9407518716a7
diff --git a/apps/server/src/routers/lambda/__tests__/file.test.ts b/apps/server/src/routers/lambda/__tests__/file.test.ts
index d5792b273f8..dc4d8615ae8 100644
--- a/apps/server/src/routers/lambda/__tests__/file.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/file.test.ts
@@ -188,6 +188,7 @@ const mockFileModelDeleteUnreferenced = vi.fn();
const mockFileModelDeleteMany = vi.fn();
const mockFileModelFindById = vi.fn();
const mockFileModelFindByIds = vi.fn();
+const mockFileModelFindKnowledgeBaseIds = vi.fn().mockResolvedValue([]);
const mockFileModelQuery = vi.fn();
const mockFileModelUpdate = vi.fn();
const mockFileModelUpdateGlobalFile = vi.fn();
@@ -205,6 +206,7 @@ vi.mock('@/database/models/file', () => ({
deleteMany: mockFileModelDeleteMany,
findById: mockFileModelFindById,
findByIds: mockFileModelFindByIds,
+ findKnowledgeBaseIds: mockFileModelFindKnowledgeBaseIds,
query: mockFileModelQuery,
update: mockFileModelUpdate,
updateGlobalFile: mockFileModelUpdateGlobalFile,
@@ -1068,6 +1070,34 @@ describe('fileRouter', () => {
expect(result.url).toBe('https://lobehub.com/f/test-id');
});
+
+ it('should expose the libraries the file belongs to', async () => {
+ mockFileModelFindById.mockResolvedValue(mockFile);
+ mockFileModelFindKnowledgeBaseIds.mockResolvedValueOnce(['kb-1']);
+
+ const result = await caller.findById({ id: 'test-id' });
+
+ expect(mockFileModelFindKnowledgeBaseIds).toHaveBeenCalledWith('test-id');
+ expect(result.knowledgeBaseIds).toEqual(['kb-1']);
+ });
+ });
+
+ describe('getReadableUrl', () => {
+ it('should throw when the file does not exist', async () => {
+ mockFileModelFindById.mockResolvedValue(null);
+
+ await expect(caller.getReadableUrl({ id: 'invalid-id' })).rejects.toThrow(TRPCError);
+ });
+
+ it('should return the storage URL instead of the /f/:id proxy', async () => {
+ mockFileModelFindById.mockResolvedValue(mockFile);
+ mockFileServiceGetFullFileUrl.mockResolvedValue('https://s3.example.com/test-url?sig=1');
+
+ const result = await caller.getReadableUrl({ id: 'test-id' });
+
+ expect(mockFileServiceGetFullFileUrl).toHaveBeenCalledWith('test-url');
+ expect(result.url).toBe('https://s3.example.com/test-url?sig=1');
+ });
});
describe('getFileItemById', () => {
diff --git a/apps/server/src/routers/lambda/file.ts b/apps/server/src/routers/lambda/file.ts
index 4aee003859a..19b5dd59731 100644
--- a/apps/server/src/routers/lambda/file.ts
+++ b/apps/server/src/routers/lambda/file.ts
@@ -465,6 +465,7 @@ export const fileRouter = router({
fileHash: item.fileHash,
fileType: item.fileType,
id: item.id,
+ knowledgeBaseIds: await ctx.fileModel.findKnowledgeBaseIds(item.id),
metadata: item.metadata,
name: item.name,
parentId: item.parentId,
@@ -473,9 +474,31 @@ export const fileRouter = router({
updatedAt: item.updatedAt,
url: await ctx.fileService.getFileAccessUrl(item),
userId: item.userId,
+ visibility: item.visibility,
};
}),
+ /**
+ * Direct storage URL for reading a file's bytes in the browser (canvas
+ * export). The `/f/:id` proxy answers with a cross-origin redirect, which
+ * drops the request's Origin so bucket CORS can never allow it; fetching the
+ * storage URL directly keeps the Origin the bucket already allows for uploads.
+ */
+ getReadableUrl: fileProcedure
+ .input(
+ z.object({
+ id: z.string(),
+ }),
+ )
+ .query(async ({ ctx, input }) => {
+ const item = await ctx.fileModel.findById(input.id);
+ if (!item) throw new TRPCError({ code: 'NOT_FOUND', message: 'File not found' });
+
+ await assertFileNotInRestrictedKnowledgeBase(ctx, input.id);
+
+ return { url: await ctx.fileService.getFullFileUrl(item.url) };
+ }),
+
getFileItemById: fileProcedure
.input(
z.object({
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index c2c93a16914..29ff23f79fb 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -49,6 +49,104 @@
"home.recentPages": "Recent Pages",
"home.uploadEntries.library.title": "Create New Library",
"home.viewAll": "View all",
+ "imageViewer.ai.brushSize": "Brush size",
+ "imageViewer.ai.cancelled": "Edit cancelled. The original image is unchanged.",
+ "imageViewer.ai.erase.empty": "Paint over an area first",
+ "imageViewer.ai.erase.hint": "Paint over what you want to erase",
+ "imageViewer.ai.erase.start": "Erase",
+ "imageViewer.ai.error.failed": "Edit failed. Hover for details. The original image is unchanged.",
+ "imageViewer.ai.error.lostTrack": "Lost track of the edit. It may still be running in Image generation, where the result will appear.",
+ "imageViewer.ai.error.noModel": "No image model that can edit images is enabled. Enable one under Settings → AI Service Provider.",
+ "imageViewer.ai.error.noResult": "The model returned no image. Try again.",
+ "imageViewer.ai.error.timeout": "Still running after 3 minutes. It keeps going in Image generation, where the result will appear.",
+ "imageViewer.ai.error.tooLarge": "This image is larger than the selected model accepts. Resize it smaller, then try again.",
+ "imageViewer.ai.phase.generating": "Generating… {{seconds}}s",
+ "imageViewer.ai.phase.saving": "Saving as a new image…",
+ "imageViewer.ai.phase.uploading": "Preparing…",
+ "imageViewer.ai.removeBackground.hint": "AI removes the background and saves the result as a new image",
+ "imageViewer.ai.removeBackground.start": "Remove background",
+ "imageViewer.ai.stoppedWaiting": "Stopped waiting. The edit keeps running in Image generation, where the result will appear.",
+ "imageViewer.ai.topicTitle": "{{operation}} · {{name}}",
+ "imageViewer.annotate.brush": "Brush",
+ "imageViewer.annotate.clear": "Clear",
+ "imageViewer.annotate.color": "Color",
+ "imageViewer.annotate.colorName.blue": "Blue",
+ "imageViewer.annotate.colorName.green": "Green",
+ "imageViewer.annotate.colorName.red": "Red",
+ "imageViewer.annotate.colorName.white": "White",
+ "imageViewer.annotate.colorName.yellow": "Yellow",
+ "imageViewer.annotate.hint": "Drag on the image to draw",
+ "imageViewer.annotate.rect": "Box",
+ "imageViewer.annotate.size": "Stroke width",
+ "imageViewer.annotate.undo": "Undo",
+ "imageViewer.cancel": "Cancel",
+ "imageViewer.close": "Close",
+ "imageViewer.comment.add": "Add comment",
+ "imageViewer.comment.count": "{{count}} comments",
+ "imageViewer.comment.delete": "Delete comment",
+ "imageViewer.comment.empty": "No comments yet. Click a point or drag over an area to add one.",
+ "imageViewer.comment.hint": "Click to pin a comment, or drag to mark an area",
+ "imageViewer.comment.pin": "Comment {{index}}",
+ "imageViewer.comment.placeholder": "Write a comment… (Enter to add)",
+ "imageViewer.comment.post": "Add",
+ "imageViewer.comment.title": "Comments",
+ "imageViewer.done": "Done",
+ "imageViewer.download": "Download",
+ "imageViewer.editTools": "Image tools",
+ "imageViewer.exitFullscreen": "Exit full screen",
+ "imageViewer.fileActions": "File actions",
+ "imageViewer.fitToScreen": "Fit to screen",
+ "imageViewer.fullscreen": "Full screen",
+ "imageViewer.loadFailed": "Failed to load the image",
+ "imageViewer.markup.addToChat": "Add to chat",
+ "imageViewer.markup.added": "Added to the chat input. Review it, then send.",
+ "imageViewer.markup.area.bottom": "bottom",
+ "imageViewer.markup.area.bottomLeft": "bottom left",
+ "imageViewer.markup.area.bottomRight": "bottom right",
+ "imageViewer.markup.area.center": "center",
+ "imageViewer.markup.area.left": "left",
+ "imageViewer.markup.area.right": "right",
+ "imageViewer.markup.area.top": "top",
+ "imageViewer.markup.area.topLeft": "top left",
+ "imageViewer.markup.area.topRight": "top right",
+ "imageViewer.markup.askInNewChat": "Ask in new chat",
+ "imageViewer.markup.discard": "Discard annotations and comments",
+ "imageViewer.markup.discardConfirm.content": "Your annotations and comments have not been added to a chat yet. Closing the viewer discards them.",
+ "imageViewer.markup.discardConfirm.ok": "Discard and close",
+ "imageViewer.markup.discardConfirm.title": "Discard unsent annotations?",
+ "imageViewer.markup.empty": "Draw or comment on the image first",
+ "imageViewer.markup.failed": "Failed to add the image to the chat",
+ "imageViewer.markup.location.point": "{{area}} (x {{x}}%, y {{y}}%)",
+ "imageViewer.markup.location.region": "area, {{area}} (x {{x1}}–{{x2}}%, y {{y1}}–{{y2}}%)",
+ "imageViewer.markup.message.drawingOnly": "See my annotations on the attached image \"{{name}}\".",
+ "imageViewer.markup.message.header": "Comments on the attached image \"{{name}}\" (numbers match the markers on the image):",
+ "imageViewer.markup.message.headerWithDrawing": "See my annotations on the attached image \"{{name}}\". Comments (numbers match the markers on the image):",
+ "imageViewer.markup.message.item": "{{index}}. {{location}}: {{text}}",
+ "imageViewer.markup.noConversation": "There is no chat to add the image to",
+ "imageViewer.pixelsUnavailable": "This image cannot be edited because its storage does not allow reading pixels",
+ "imageViewer.resize.aspect.free": "Free",
+ "imageViewer.resize.aspect.original": "Original",
+ "imageViewer.resize.aspectLabel": "Aspect ratio",
+ "imageViewer.resize.height": "Height",
+ "imageViewer.resize.lock": "Lock aspect ratio",
+ "imageViewer.resize.width": "Width",
+ "imageViewer.retry": "Retry",
+ "imageViewer.rotate": "Rotate",
+ "imageViewer.saveAsNew": "Save as new image",
+ "imageViewer.saveFailed": "Failed to save the image",
+ "imageViewer.saved": "Saved as {{name}}",
+ "imageViewer.savedNotInLibrary": "Saved as {{name}}, but it could not be added to the original's library. Add it from the file menu.",
+ "imageViewer.saving": "Saving…",
+ "imageViewer.tool.annotate": "Annotate",
+ "imageViewer.tool.comment": "Comment",
+ "imageViewer.tool.erase": "Erase",
+ "imageViewer.tool.removeBackground": "Remove background",
+ "imageViewer.tool.resize": "Resize",
+ "imageViewer.version.label": "Versions",
+ "imageViewer.version.original": "Original",
+ "imageViewer.zoom": "Zoom",
+ "imageViewer.zoomIn": "Zoom in",
+ "imageViewer.zoomOut": "Zoom out",
"library.backToResources": "Back to Resources",
"library.hierarchy.empty.desc": "Add files or create a folder to get started",
"library.hierarchy.empty.title": "Nothing here yet",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 4858d2e0b6e..f01d9198e5f 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -49,6 +49,104 @@
"home.recentPages": "最近文稿",
"home.uploadEntries.library.title": "新建资源库",
"home.viewAll": "查看全部",
+ "imageViewer.ai.brushSize": "笔刷大小",
+ "imageViewer.ai.cancelled": "已取消编辑,原图未改动",
+ "imageViewer.ai.erase.empty": "请先涂抹要擦除的区域",
+ "imageViewer.ai.erase.hint": "涂抹要擦除的区域",
+ "imageViewer.ai.erase.start": "擦除",
+ "imageViewer.ai.error.failed": "编辑失败,悬停查看详情。原图未改动",
+ "imageViewer.ai.error.lostTrack": "暂时无法获取编辑进度,任务可能仍在「图片生成」中运行,结果会出现在那里",
+ "imageViewer.ai.error.noModel": "没有可编辑图片的已启用模型,请在「设置 → AI 服务商」中启用一个图片模型",
+ "imageViewer.ai.error.noResult": "模型没有返回图片,请重试",
+ "imageViewer.ai.error.timeout": "已运行超过 3 分钟,任务仍在「图片生成」中继续,结果会出现在那里",
+ "imageViewer.ai.error.tooLarge": "图片超出当前模型可接受的大小,请先调整大小后再试",
+ "imageViewer.ai.phase.generating": "生成中… {{seconds}} 秒",
+ "imageViewer.ai.phase.saving": "正在保存为新图片…",
+ "imageViewer.ai.phase.uploading": "准备中…",
+ "imageViewer.ai.removeBackground.hint": "AI 将移除背景,并把结果另存为新图片",
+ "imageViewer.ai.removeBackground.start": "移除背景",
+ "imageViewer.ai.stoppedWaiting": "已停止等待,编辑仍在「图片生成」中继续,结果会出现在那里",
+ "imageViewer.ai.topicTitle": "{{operation}} · {{name}}",
+ "imageViewer.annotate.brush": "画笔",
+ "imageViewer.annotate.clear": "清空",
+ "imageViewer.annotate.color": "颜色",
+ "imageViewer.annotate.colorName.blue": "蓝色",
+ "imageViewer.annotate.colorName.green": "绿色",
+ "imageViewer.annotate.colorName.red": "红色",
+ "imageViewer.annotate.colorName.white": "白色",
+ "imageViewer.annotate.colorName.yellow": "黄色",
+ "imageViewer.annotate.hint": "在图片上拖动进行绘制",
+ "imageViewer.annotate.rect": "框选",
+ "imageViewer.annotate.size": "线条粗细",
+ "imageViewer.annotate.undo": "撤销",
+ "imageViewer.cancel": "取消",
+ "imageViewer.close": "关闭",
+ "imageViewer.comment.add": "添加评论",
+ "imageViewer.comment.count": "{{count}} 条评论",
+ "imageViewer.comment.delete": "删除评论",
+ "imageViewer.comment.empty": "还没有评论,点击某个位置或拖出一个区域来添加",
+ "imageViewer.comment.hint": "点击钉一条评论,或拖动框选一个区域",
+ "imageViewer.comment.pin": "评论 {{index}}",
+ "imageViewer.comment.placeholder": "写下评论…(Enter 添加)",
+ "imageViewer.comment.post": "添加",
+ "imageViewer.comment.title": "评论",
+ "imageViewer.done": "完成",
+ "imageViewer.download": "下载",
+ "imageViewer.editTools": "图片工具",
+ "imageViewer.exitFullscreen": "退出全屏",
+ "imageViewer.fileActions": "文件操作",
+ "imageViewer.fitToScreen": "适应屏幕",
+ "imageViewer.fullscreen": "全屏",
+ "imageViewer.loadFailed": "图片加载失败",
+ "imageViewer.markup.addToChat": "添加到对话",
+ "imageViewer.markup.added": "已加入对话输入框,确认后发送",
+ "imageViewer.markup.area.bottom": "底部",
+ "imageViewer.markup.area.bottomLeft": "左下",
+ "imageViewer.markup.area.bottomRight": "右下",
+ "imageViewer.markup.area.center": "中间",
+ "imageViewer.markup.area.left": "左侧",
+ "imageViewer.markup.area.right": "右侧",
+ "imageViewer.markup.area.top": "顶部",
+ "imageViewer.markup.area.topLeft": "左上",
+ "imageViewer.markup.area.topRight": "右上",
+ "imageViewer.markup.askInNewChat": "在新对话中提问",
+ "imageViewer.markup.discard": "清除标注和评论",
+ "imageViewer.markup.discardConfirm.content": "标注和评论还没有添加到对话,关闭查看器后会被清除。",
+ "imageViewer.markup.discardConfirm.ok": "清除并关闭",
+ "imageViewer.markup.discardConfirm.title": "清除未发送的标注?",
+ "imageViewer.markup.empty": "先在图片上标注或评论",
+ "imageViewer.markup.failed": "图片添加到对话失败",
+ "imageViewer.markup.location.point": "{{area}}(x {{x}}%,y {{y}}%)",
+ "imageViewer.markup.location.region": "{{area}}区域(x {{x1}}–{{x2}}%,y {{y1}}–{{y2}}%)",
+ "imageViewer.markup.message.drawingOnly": "请看附图「{{name}}」上的标注。",
+ "imageViewer.markup.message.header": "关于附图「{{name}}」的评论(编号对应图上的标记):",
+ "imageViewer.markup.message.headerWithDrawing": "请看附图「{{name}}」上的标注。评论(编号对应图上的标记):",
+ "imageViewer.markup.message.item": "{{index}}. {{location}}:{{text}}",
+ "imageViewer.markup.noConversation": "没有可以添加图片的对话",
+ "imageViewer.pixelsUnavailable": "图片存储不允许读取像素,无法编辑",
+ "imageViewer.resize.aspect.free": "自由",
+ "imageViewer.resize.aspect.original": "原始比例",
+ "imageViewer.resize.aspectLabel": "比例",
+ "imageViewer.resize.height": "高",
+ "imageViewer.resize.lock": "锁定比例",
+ "imageViewer.resize.width": "宽",
+ "imageViewer.retry": "重试",
+ "imageViewer.rotate": "旋转",
+ "imageViewer.saveAsNew": "另存为新图片",
+ "imageViewer.saveFailed": "图片保存失败",
+ "imageViewer.saved": "已另存为 {{name}}",
+ "imageViewer.savedNotInLibrary": "已另存为 {{name}},但未能加入原图所在的资源库,可在文件菜单中手动添加",
+ "imageViewer.saving": "保存中…",
+ "imageViewer.tool.annotate": "标注",
+ "imageViewer.tool.comment": "评论",
+ "imageViewer.tool.erase": "擦除",
+ "imageViewer.tool.removeBackground": "移除背景",
+ "imageViewer.tool.resize": "调整大小",
+ "imageViewer.version.label": "版本",
+ "imageViewer.version.original": "原图",
+ "imageViewer.zoom": "缩放",
+ "imageViewer.zoomIn": "放大",
+ "imageViewer.zoomOut": "缩小",
"library.backToResources": "返回资源库",
"library.hierarchy.empty.desc": "上传文件或新建文件夹开始整理",
"library.hierarchy.empty.title": "这里还没有内容",
diff --git a/packages/database/src/models/__tests__/file.test.ts b/packages/database/src/models/__tests__/file.test.ts
index e7f3a6aef24..e3ee640b068 100644
--- a/packages/database/src/models/__tests__/file.test.ts
+++ b/packages/database/src/models/__tests__/file.test.ts
@@ -1026,6 +1026,53 @@ describe('FileModel', () => {
});
});
+ describe('findKnowledgeBaseIds', () => {
+ it('lists the libraries a file is filed in', async () => {
+ const { id } = await fileModel.create({
+ fileType: 'image/png',
+ name: 'photo.png',
+ size: 100,
+ url: 'files/photo.png',
+ });
+ await serverDB
+ .insert(knowledgeBaseFiles)
+ .values({ fileId: id, knowledgeBaseId: 'kb1', userId });
+
+ expect(await fileModel.findKnowledgeBaseIds(id)).toEqual(['kb1']);
+ });
+
+ // Regression: a collaborator's private library leaked into the caller's
+ // list, and saving an edit then tried to write to it.
+ it('omits libraries the caller cannot see', async () => {
+ const { id } = await fileModel.create({
+ fileType: 'image/png',
+ name: 'shared.png',
+ size: 100,
+ url: 'files/shared.png',
+ });
+ await serverDB
+ .insert(knowledgeBases)
+ .values({ id: 'kb_other_private', name: 'theirs', userId: 'user2' });
+ await serverDB.insert(knowledgeBaseFiles).values([
+ { fileId: id, knowledgeBaseId: 'kb1', userId },
+ { fileId: id, knowledgeBaseId: 'kb_other_private', userId: 'user2' },
+ ]);
+
+ expect(await fileModel.findKnowledgeBaseIds(id)).toEqual(['kb1']);
+ });
+
+ it('returns an empty list for a file outside any library', async () => {
+ const { id } = await fileModel.create({
+ fileType: 'image/png',
+ name: 'loose.png',
+ size: 100,
+ url: 'files/loose.png',
+ });
+
+ expect(await fileModel.findKnowledgeBaseIds(id)).toEqual([]);
+ });
+ });
+
describe('findById', () => {
it('should find a file by id', async () => {
const { id } = await fileModel.create({
diff --git a/packages/database/src/models/__tests__/generation.test.ts b/packages/database/src/models/__tests__/generation.test.ts
index e015c545df3..59172a53931 100644
--- a/packages/database/src/models/__tests__/generation.test.ts
+++ b/packages/database/src/models/__tests__/generation.test.ts
@@ -692,6 +692,7 @@ describe('GenerationModel', () => {
const result = await generationModel.transformGeneration(generationWithTask);
expect(result).toMatchObject({
+ fileId: 'file-id',
id: 'test-gen-id',
asset: {
url: 'https://example.com/f/file-id',
@@ -745,6 +746,7 @@ describe('GenerationModel', () => {
const result = await generationModel.transformGeneration(generationWithoutAsset as any);
+ expect(result).not.toHaveProperty('fileId');
expect(result).toMatchObject({
id: 'test-gen-id',
asset: null,
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index 8bd352a7fab..8f4717956e7 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -37,6 +37,7 @@ import {
generations,
globalFiles,
knowledgeBaseFiles,
+ knowledgeBases,
messages,
messagesFiles,
messageTTS,
@@ -610,6 +611,28 @@ export class FileModel {
});
};
+ /**
+ * Libraries (knowledge bases) a file is filed in that the caller can see. A
+ * collaborator may have filed it into their own private library, which the
+ * caller must neither learn about nor write to.
+ */
+ findKnowledgeBaseIds = async (fileId: string): Promise<string[]> => {
+ const rows = await this.db
+ .select({ id: knowledgeBaseFiles.knowledgeBaseId })
+ .from(knowledgeBaseFiles)
+ .innerJoin(knowledgeBases, eq(knowledgeBases.id, knowledgeBaseFiles.knowledgeBaseId))
+ .where(
+ and(
+ eq(knowledgeBaseFiles.fileId, fileId),
+ buildWorkspaceWhere(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ knowledgeBases,
+ ),
+ ),
+ );
+ return rows.map((row) => row.id);
+ };
+
findById = async (
id: string,
options: { accessScope?: FileAccessScope; transaction?: Transaction } = {},
diff --git a/packages/database/src/models/generation.ts b/packages/database/src/models/generation.ts
index f3eb489ba87..bd81a289bb9 100644
--- a/packages/database/src/models/generation.ts
+++ b/packages/database/src/models/generation.ts
@@ -259,6 +259,7 @@ export class GenerationModel {
asset,
asyncTaskId: generation.asyncTaskId || null,
createdAt: generation.createdAt,
+ ...(generation.fileId ? { fileId: generation.fileId } : {}),
id: generation.id,
...(previousGenerationId ? { previousGenerationId } : {}),
seed: generation.seed,
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 712ef41d159..c5b7b0f997e 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -103,6 +103,115 @@ export default {
'Create Libraries and add files to build your own Library.',
'notSupportGuide.features.libraries.title': 'Library',
'notSupportGuide.title': 'The current deployment mode does not support file management',
+ 'imageViewer.ai.brushSize': 'Brush size',
+ 'imageViewer.ai.cancelled': 'Edit cancelled. The original image is unchanged.',
+ 'imageViewer.ai.erase.empty': 'Paint over an area first',
+ 'imageViewer.ai.erase.hint': 'Paint over what you want to erase',
+ 'imageViewer.ai.erase.start': 'Erase',
+ 'imageViewer.ai.error.failed': 'Edit failed. Hover for details. The original image is unchanged.',
+ 'imageViewer.ai.error.lostTrack':
+ 'Lost track of the edit. It may still be running in Image generation, where the result will appear.',
+ 'imageViewer.ai.error.noModel':
+ 'No image model that can edit images is enabled. Enable one under Settings → AI Service Provider.',
+ 'imageViewer.ai.error.noResult': 'The model returned no image. Try again.',
+ 'imageViewer.ai.error.timeout':
+ 'Still running after 3 minutes. It keeps going in Image generation, where the result will appear.',
+ 'imageViewer.ai.error.tooLarge':
+ 'This image is larger than the selected model accepts. Resize it smaller, then try again.',
+ 'imageViewer.ai.phase.generating': 'Generating… {{seconds}}s',
+ 'imageViewer.ai.phase.saving': 'Saving as a new image…',
+ 'imageViewer.ai.phase.uploading': 'Preparing…',
+ 'imageViewer.ai.removeBackground.hint':
+ 'AI removes the background and saves the result as a new image',
+ 'imageViewer.ai.removeBackground.start': 'Remove background',
+ 'imageViewer.ai.topicTitle': '{{operation}} · {{name}}',
+ 'imageViewer.tool.annotate': 'Annotate',
+ 'imageViewer.tool.erase': 'Erase',
+ 'imageViewer.tool.removeBackground': 'Remove background',
+ 'imageViewer.annotate.brush': 'Brush',
+ 'imageViewer.annotate.clear': 'Clear',
+ 'imageViewer.annotate.color': 'Color',
+ 'imageViewer.annotate.colorName.red': 'Red',
+ 'imageViewer.annotate.colorName.yellow': 'Yellow',
+ 'imageViewer.annotate.colorName.green': 'Green',
+ 'imageViewer.annotate.colorName.blue': 'Blue',
+ 'imageViewer.annotate.colorName.white': 'White',
+ 'imageViewer.annotate.hint': 'Drag on the image to draw',
+ 'imageViewer.annotate.rect': 'Box',
+ 'imageViewer.annotate.size': 'Stroke width',
+ 'imageViewer.annotate.undo': 'Undo',
+ 'imageViewer.ai.stoppedWaiting':
+ 'Stopped waiting. The edit keeps running in Image generation, where the result will appear.',
+ 'imageViewer.markup.added': 'Added to the chat input. Review it, then send.',
+ 'imageViewer.markup.addToChat': 'Add to chat',
+ 'imageViewer.markup.area.bottom': 'bottom',
+ 'imageViewer.markup.area.bottomLeft': 'bottom left',
+ 'imageViewer.markup.area.bottomRight': 'bottom right',
+ 'imageViewer.markup.area.center': 'center',
+ 'imageViewer.markup.area.left': 'left',
+ 'imageViewer.markup.area.right': 'right',
+ 'imageViewer.markup.area.top': 'top',
+ 'imageViewer.markup.area.topLeft': 'top left',
+ 'imageViewer.markup.area.topRight': 'top right',
+ 'imageViewer.markup.askInNewChat': 'Ask in new chat',
+ 'imageViewer.markup.discard': 'Discard annotations and comments',
+ 'imageViewer.markup.discardConfirm.content':
+ 'Your annotations and comments have not been added to a chat yet. Closing the viewer discards them.',
+ 'imageViewer.markup.discardConfirm.ok': 'Discard and close',
+ 'imageViewer.markup.discardConfirm.title': 'Discard unsent annotations?',
+ 'imageViewer.markup.empty': 'Draw or comment on the image first',
+ 'imageViewer.markup.failed': 'Failed to add the image to the chat',
+ 'imageViewer.markup.location.point': '{{area}} (x {{x}}%, y {{y}}%)',
+ 'imageViewer.markup.location.region': 'area, {{area}} (x {{x1}}–{{x2}}%, y {{y1}}–{{y2}}%)',
+ 'imageViewer.markup.message.drawingOnly': 'See my annotations on the attached image "{{name}}".',
+ 'imageViewer.markup.message.item': '{{index}}. {{location}}: {{text}}',
+ 'imageViewer.markup.message.header':
+ 'Comments on the attached image "{{name}}" (numbers match the markers on the image):',
+ 'imageViewer.markup.message.headerWithDrawing':
+ 'See my annotations on the attached image "{{name}}". Comments (numbers match the markers on the image):',
+ 'imageViewer.markup.noConversation': 'There is no chat to add the image to',
+ 'imageViewer.cancel': 'Cancel',
+ 'imageViewer.close': 'Close',
+ 'imageViewer.tool.comment': 'Comment',
+ 'imageViewer.comment.add': 'Add comment',
+ 'imageViewer.comment.count': '{{count}} comments',
+ 'imageViewer.comment.delete': 'Delete comment',
+ 'imageViewer.comment.empty': 'No comments yet. Click a point or drag over an area to add one.',
+ 'imageViewer.comment.hint': 'Click to pin a comment, or drag to mark an area',
+ 'imageViewer.comment.pin': 'Comment {{index}}',
+ 'imageViewer.comment.placeholder': 'Write a comment… (Enter to add)',
+ 'imageViewer.comment.post': 'Add',
+ 'imageViewer.comment.title': 'Comments',
+ 'imageViewer.done': 'Done',
+ 'imageViewer.download': 'Download',
+ 'imageViewer.editTools': 'Image tools',
+ 'imageViewer.exitFullscreen': 'Exit full screen',
+ 'imageViewer.fileActions': 'File actions',
+ 'imageViewer.fitToScreen': 'Fit to screen',
+ 'imageViewer.fullscreen': 'Full screen',
+ 'imageViewer.loadFailed': 'Failed to load the image',
+ 'imageViewer.pixelsUnavailable':
+ 'This image cannot be edited because its storage does not allow reading pixels',
+ 'imageViewer.tool.resize': 'Resize',
+ 'imageViewer.resize.aspectLabel': 'Aspect ratio',
+ 'imageViewer.resize.aspect.free': 'Free',
+ 'imageViewer.resize.aspect.original': 'Original',
+ 'imageViewer.resize.height': 'Height',
+ 'imageViewer.resize.lock': 'Lock aspect ratio',
+ 'imageViewer.resize.width': 'Width',
+ 'imageViewer.retry': 'Retry',
+ 'imageViewer.rotate': 'Rotate',
+ 'imageViewer.saveAsNew': 'Save as new image',
+ 'imageViewer.saveFailed': 'Failed to save the image',
+ 'imageViewer.saved': 'Saved as {{name}}',
+ 'imageViewer.savedNotInLibrary':
+ "Saved as {{name}}, but it could not be added to the original's library. Add it from the file menu.",
+ 'imageViewer.saving': 'Saving…',
+ 'imageViewer.version.label': 'Versions',
+ 'imageViewer.version.original': 'Original',
+ 'imageViewer.zoom': 'Zoom',
+ 'imageViewer.zoomIn': 'Zoom in',
+ 'imageViewer.zoomOut': 'Zoom out',
'pageEditor.addIcon': 'Add Icon',
'pageEditor.autoSaveMessage': 'Your page is saved automatically. No need to save manually.',
'pageEditor.chooseIcon': 'Choose Icon',
diff --git a/packages/types/src/generation/index.ts b/packages/types/src/generation/index.ts
index 3f4dd8c2c68..faabfda7775 100644
--- a/packages/types/src/generation/index.ts
+++ b/packages/types/src/generation/index.ts
@@ -88,6 +88,10 @@ export interface Generation {
asset?: GenerationAsset | null;
asyncTaskId: string | null;
createdAt: Date;
+ /**
+ * Library file the generated asset was saved as, once the task succeeded.
+ */
+ fileId?: string | null;
id: string;
/**
* Source generation this one edits, read from the async task metadata so the
diff --git a/src/features/Conversation/ComposerDraftReceiver.test.tsx b/src/features/Conversation/ComposerDraftReceiver.test.tsx
index af7a351b578..b599ef1530b 100644
--- a/src/features/Conversation/ComposerDraftReceiver.test.tsx
+++ b/src/features/Conversation/ComposerDraftReceiver.test.tsx
@@ -1,23 +1,40 @@
import { act, render } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { draftToMainComposer, useComposerDraftBus } from './composerDraftBus';
+import {
+ draftToMainComposer,
+ queueDraftForMainComposer,
+ useComposerDraftBus,
+} from './composerDraftBus';
import ComposerDraftReceiver from './ComposerDraftReceiver';
const mocks = vi.hoisted(() => ({
- editor: null as null | { focus: ReturnType<typeof vi.fn>; setDocument: ReturnType<typeof vi.fn> },
+ editor: null as null | {
+ focus: ReturnType<typeof vi.fn>;
+ getMarkdownContent?: () => string;
+ setDocument: ReturnType<typeof vi.fn>;
+ },
+ context: { agentId: 'agt_inbox', topicId: undefined as string | undefined },
+ inputMessage: '',
updateInputMessage: vi.fn(),
}));
vi.mock('./store', () => ({
useConversationStore: (selector: (s: unknown) => unknown) =>
- selector({ editor: mocks.editor, updateInputMessage: mocks.updateInputMessage }),
+ selector({
+ context: mocks.context,
+ editor: mocks.editor,
+ updateInputMessage: mocks.updateInputMessage,
+ }),
+ useConversationStoreApi: () => ({ getState: () => ({ inputMessage: mocks.inputMessage }) }),
}));
describe('ComposerDraftReceiver', () => {
beforeEach(() => {
useComposerDraftBus.setState({ attached: false, draft: null });
mocks.editor = null;
+ mocks.inputMessage = '';
+ mocks.context = { agentId: 'agt_inbox', topicId: undefined };
mocks.updateInputMessage.mockClear();
});
@@ -47,6 +64,83 @@ describe('ComposerDraftReceiver', () => {
expect(useComposerDraftBus.getState().draft).toBeNull();
});
+ it('appends after what the user already typed when asked to', () => {
+ mocks.editor = { focus: vi.fn(), setDocument: vi.fn() };
+ mocks.inputMessage = 'what is wrong here?';
+ render(<ComposerDraftReceiver />);
+
+ act(() => {
+ draftToMainComposer('1. top left: this logo', { append: true });
+ });
+
+ const text = 'what is wrong here?\n\n1. top left: this logo';
+ expect(mocks.editor.setDocument).toHaveBeenCalledWith('markdown', text);
+ expect(mocks.updateInputMessage).toHaveBeenCalledWith(text);
+ });
+
+ // Regression: appending trimmed the typed text, losing a trailing Markdown break.
+ it('keeps the whitespace of what the user typed when appending', () => {
+ mocks.editor = { focus: vi.fn(), setDocument: vi.fn() };
+ mocks.inputMessage = ' indented line ';
+ render(<ComposerDraftReceiver />);
+
+ act(() => {
+ draftToMainComposer('1. note', { append: true });
+ });
+
+ expect(mocks.editor.setDocument).toHaveBeenCalledWith(
+ 'markdown',
+ ' indented line \n\n1. note',
+ );
+ });
+
+ // Regression: `inputMessage` trails the editor behind a debounce; appending
+ // to it overwrote the characters typed just before Add to chat.
+ it('appends to the live editor content, not its delayed mirror', () => {
+ // The conversation store holds the ChatInputEditor wrapper.
+ const editor = {
+ focus: vi.fn(),
+ getMarkdownContent: () => 'typed just now',
+ setDocument: vi.fn(),
+ };
+ mocks.editor = editor;
+ mocks.inputMessage = 'typed';
+ render(<ComposerDraftReceiver />);
+
+ act(() => {
+ draftToMainComposer('1. note', { append: true });
+ });
+
+ expect(editor.setDocument).toHaveBeenCalledWith('markdown', 'typed just now\n\n1. note');
+ });
+
+ it('applies a queued draft once a composer mounts', () => {
+ queueDraftForMainComposer('queued before navigation', { agentId: 'agt_inbox' });
+ mocks.editor = { focus: vi.fn(), setDocument: vi.fn() };
+ render(<ComposerDraftReceiver />);
+
+ expect(mocks.editor.setDocument).toHaveBeenCalledWith('markdown', 'queued before navigation');
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ });
+
+ // Regression: right after navigating, the conversation is still on the
+ // previously active topic; the switch to the new topic clears the input.
+ it('holds a queued draft until the conversation reaches the target new topic', () => {
+ queueDraftForMainComposer('queued before navigation', { agentId: 'agt_inbox' });
+ mocks.editor = { focus: vi.fn(), setDocument: vi.fn() };
+ mocks.context = { agentId: 'agt_inbox', topicId: 'tpc_previous' };
+ const { rerender } = render(<ComposerDraftReceiver />);
+
+ expect(mocks.editor.setDocument).not.toHaveBeenCalled();
+ expect(useComposerDraftBus.getState().draft).not.toBeNull();
+
+ // The mocked store is not reactive; a fresh render stands in for its update.
+ mocks.context = { agentId: 'agt_inbox', topicId: undefined };
+ rerender(<ComposerDraftReceiver key={'settled'} />);
+
+ expect(mocks.editor.setDocument).toHaveBeenCalledWith('markdown', 'queued before navigation');
+ });
+
it('stays detached without an editor, so posting reports failure', () => {
render(<ComposerDraftReceiver />);
expect(useComposerDraftBus.getState().attached).toBe(false);
diff --git a/src/features/Conversation/ComposerDraftReceiver.tsx b/src/features/Conversation/ComposerDraftReceiver.tsx
index 10bbd591b95..d2310e0a2b6 100644
--- a/src/features/Conversation/ComposerDraftReceiver.tsx
+++ b/src/features/Conversation/ComposerDraftReceiver.tsx
@@ -3,7 +3,7 @@
import { memo, useEffect } from 'react';
import { useComposerDraftBus } from './composerDraftBus';
-import { useConversationStore } from './store';
+import { useConversationStore, useConversationStoreApi } from './store';
/**
* Renders nothing — consumes composerDraftBus drafts into the live composer.
@@ -16,6 +16,9 @@ import { useConversationStore } from './store';
const ComposerDraftReceiver = memo(() => {
const editor = useConversationStore((s) => s.editor);
const updateInputMessage = useConversationStore((s) => s.updateInputMessage);
+ const agentId = useConversationStore((s) => s.context.agentId);
+ const topicId = useConversationStore((s) => s.context.topicId);
+ const storeApi = useConversationStoreApi();
const draft = useComposerDraftBus((s) => s.draft);
useEffect(() => {
@@ -27,13 +30,23 @@ const ComposerDraftReceiver = memo(() => {
useEffect(() => {
if (!draft || !editor) return;
+ // Right after navigating, the conversation still points at the previously
+ // active topic; switching away clears the input. Wait for the new topic.
+ if (draft.target && (draft.target.agentId !== agentId || topicId)) return;
+ // Keep what the user typed as is (indentation, Markdown line breaks); only
+ // an all-blank input counts as empty.
+ // Read the editor itself (a ChatInputEditor): `inputMessage` trails it
+ // behind a debounce, and the last few typed characters would be lost.
+ const live: unknown = draft.append ? editor.getMarkdownContent?.() : undefined;
+ const current = typeof live === 'string' ? live : storeApi.getState().inputMessage;
+ const text = draft.append && current.trim() ? `${current}\n\n${draft.text}` : draft.text;
// setDocument alone does not fire the change handler that keeps
// inputMessage in sync — Send would stay disabled (see restoreToInput).
- editor.setDocument('markdown', draft.text);
- updateInputMessage(draft.text);
+ editor.setDocument('markdown', text);
+ updateInputMessage(text);
editor.focus();
useComposerDraftBus.setState({ draft: null });
- }, [draft, editor, updateInputMessage]);
+ }, [agentId, draft, editor, storeApi, topicId, updateInputMessage]);
return null;
});
diff --git a/src/features/Conversation/composerDraftBus.ts b/src/features/Conversation/composerDraftBus.ts
index 425bc346195..d3cc53d52eb 100644
--- a/src/features/Conversation/composerDraftBus.ts
+++ b/src/features/Conversation/composerDraftBus.ts
@@ -14,8 +14,13 @@ import { createWithEqualityFn } from 'zustand/traditional';
interface ComposerDraftBusState {
/** A receiver with a live editor is mounted and will consume drafts. */
attached: boolean;
- /** The pending draft, cleared by the receiver once applied. */
- draft: { text: string } | null;
+ /**
+ * The pending draft, cleared by the receiver once applied. `append` adds it
+ * after what the user already typed instead of replacing it. A draft with a
+ * `target` waits until the conversation has settled on that agent's new
+ * topic, so the topic switch that follows a navigation cannot wipe it.
+ */
+ draft: { append?: boolean; target?: { agentId: string }; text: string } | null;
}
export const useComposerDraftBus = createWithEqualityFn<ComposerDraftBusState>()(() => ({
@@ -29,8 +34,19 @@ export const useComposerDraftBus = createWithEqualityFn<ComposerDraftBusState>()
* can skip its success feedback — same contract the portal previously got
* from a null editor.
*/
-export const draftToMainComposer = (text: string): boolean => {
+export const draftToMainComposer = (
+ text: string,
+ { append }: { append?: boolean } = {},
+): boolean => {
if (!useComposerDraftBus.getState().attached) return false;
- useComposerDraftBus.setState({ draft: { text } });
+ useComposerDraftBus.setState({ draft: { append, text } });
return true;
};
+
+/**
+ * Leave a draft for a new topic of `agentId`, for a surface that navigates
+ * into that conversation right after posting.
+ */
+export const queueDraftForMainComposer = (text: string, target: { agentId: string }) => {
+ useComposerDraftBus.setState({ draft: { target, text } });
+};
diff --git a/src/features/FileViewer/ImageEditTools.ts b/src/features/FileViewer/ImageEditTools.ts
new file mode 100644
index 00000000000..2d32ac12730
--- /dev/null
+++ b/src/features/FileViewer/ImageEditTools.ts
@@ -0,0 +1 @@
+export { default } from './Renderer/Image/Tools';
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/deps.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/deps.ts
new file mode 100644
index 00000000000..d07147bd0de
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/deps.ts
@@ -0,0 +1,63 @@
+import { lambdaClient } from '@/libs/trpc/client';
+import { cutOutFlatBackground } from '@/services/artworkGeneration/cutOutFlatBackground';
+import { fileService } from '@/services/file';
+import { generationService } from '@/services/generation';
+import { generationTopicService } from '@/services/generationTopic';
+import { imageService } from '@/services/image';
+import { knowledgeBaseService } from '@/services/knowledgeBase';
+import { useFileStore } from '@/store/file';
+
+import { loadReadableImage } from '../exportImage';
+import type { AIEditDeps } from './runAIImageEdit';
+
+/** The real pipeline: the same image generation services the image page uses. */
+export const aiEditDeps: AIEditDeps = {
+ addToKnowledgeBase: (knowledgeBaseId, fileIds) =>
+ knowledgeBaseService.addFilesToKnowledgeBase(knowledgeBaseId, fileIds),
+ createImage: (payload) => imageService.createImage(payload),
+ createTopic: (title, visibility) =>
+ generationTopicService.createTopic('image', visibility, title),
+ cutOutBackground: async (url, name) => {
+ const img = await loadStageImage(url);
+ const canvas = document.createElement('canvas');
+ canvas.width = img.naturalWidth;
+ canvas.height = img.naturalHeight;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+ ctx.drawImage(img, 0, 0);
+ const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ // Same framing as the original, so no crop to the subject here.
+ if (!cutOutFlatBackground(pixels).applied) return;
+ ctx.putImageData(pixels, 0, 0);
+ const blob = await new Promise<Blob | null>((resolve) => canvas.toBlob(resolve, 'image/png'));
+ return blob ? new File([blob], name, { type: 'image/png' }) : undefined;
+ },
+ deleteTopic: (id) => generationTopicService.deleteTopic(id),
+ getFile: async (id) => {
+ const file = await lambdaClient.file.findById.query({ id });
+ return {
+ knowledgeBaseIds: file.knowledgeBaseIds,
+ metadata: file.metadata as Record<string, unknown> | null,
+ parentId: file.parentId,
+ size: file.size,
+ visibility: file.visibility,
+ };
+ },
+ getStatus: (generationId, asyncTaskId) =>
+ generationService.getGenerationStatus(generationId, asyncTaskId),
+ removeFile: (id) => fileService.removeFile(id),
+ updateFile: (id, data) => fileService.updateFile(id, data),
+ uploadFile: async ({ file, metadata, parentId, visibility }) => {
+ const result = await useFileStore.getState().uploadWithProgress({
+ file,
+ fileMetadata: metadata,
+ parentId,
+ visibility,
+ });
+ return result && { id: result.id, url: result.url };
+ },
+};
+
+/** Load the image on stage for canvas export, reading `/f/:id` files from storage directly. */
+export const loadStageImage = (url: string) =>
+ loadReadableImage(url, { resolveProxyUrl: (id) => fileService.getReadableUrl(id) });
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/fixtures.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/fixtures.ts
new file mode 100644
index 00000000000..b6d1b8f7749
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/fixtures.ts
@@ -0,0 +1,97 @@
+import type { AIEditDeps } from './runAIImageEdit';
+
+/**
+ * Shapes captured from one real `image.createImage` → `generation.getGenerationStatus`
+ * round trip (lobehub / gemini-3.1-flash-image:image, remove background). Tests and
+ * acceptance replay these instead of calling the model again.
+ */
+export const realCreateImageResult = {
+ data: {
+ batch: {
+ config: {
+ imageUrls: [
+ 'files/2026-10-05/34168abd994ba81ca274d39535fb3561608764ff5fb707a7814e734139c0870d.png',
+ ],
+ prompt: 'Remove the background of this image.',
+ },
+ generationTopicId: 'gt_6p9nBZERtyWe',
+ height: null,
+ id: 'gb_L80eFud827rr',
+ model: 'gemini-3.1-flash-image:image',
+ provider: 'lobehub',
+ width: null,
+ },
+ generations: [
+ {
+ asset: null,
+ asyncTaskId: '0f070379-d3ef-4038-9cfb-c88764b63399',
+ fileId: null,
+ generationBatchId: 'gb_L80eFud827rr',
+ id: 'gen_IUVYApnU4NYX',
+ seed: null,
+ },
+ ],
+ },
+ success: true,
+};
+
+export const realProcessingStatus = { error: null, generation: null, status: 'processing' };
+
+export const realSuccessStatus = {
+ error: null,
+ generation: {
+ asset: {
+ height: 843,
+ originalUrl: 'generations/images/EUNmLlU476d4SS8D9eTsY_1264x843_20261004_165918_raw.png',
+ thumbnailUrl:
+ 'https://storage.example.com/generations/images/EUNmLlU476d4SS8D9eTsY_512x341_20261004_165918_thumb.webp',
+ type: 'image',
+ url: 'https://app.lobehub.com/f/file_KWGzzbWzaunM',
+ width: 1264,
+ },
+ asyncTaskId: '0f070379-d3ef-4038-9cfb-c88764b63399',
+ createdAt: new Date('2026-10-04T16:59:07.945Z'),
+ // Reported once the server exposes the generation's file (this change).
+ fileId: 'file_KWGzzbWzaunM',
+ id: 'gen_IUVYApnU4NYX',
+ seed: null,
+ task: { id: '0f070379-d3ef-4038-9cfb-c88764b63399', status: 'success' },
+ },
+ status: 'success',
+};
+
+/** Metadata the generation pipeline stores on the result file. */
+export const realResultFileMetadata = {
+ generationId: 'gen_IUVYApnU4NYX',
+ height: 843,
+ path: 'generations/images/EUNmLlU476d4SS8D9eTsY_1264x843_20261004_165918_raw.png',
+ width: 1264,
+};
+
+/** Failure shape follows `AsyncTaskError` (`{ name, body: { detail } }`); not captured live. */
+export const errorStatus = {
+ error: { body: { detail: 'Content blocked by the provider safety filter' }, name: 'ServerError' },
+ generation: null,
+ status: 'error',
+};
+
+export const createMockDeps = (overrides: Partial<AIEditDeps> = {}) => {
+ const deps = {
+ addToKnowledgeBase: async () => undefined,
+ createImage: async () => realCreateImageResult,
+ createTopic: async () => 'gt_6p9nBZERtyWe',
+ // The real keying needs a canvas; tests opt in per case.
+ cutOutBackground: async () => undefined,
+ deleteTopic: async () => undefined,
+ getFile: async (id: string) =>
+ id === 'file_KWGzzbWzaunM'
+ ? { metadata: realResultFileMetadata, parentId: null }
+ : { knowledgeBaseIds: [], metadata: {}, parentId: 'docs_folder' },
+ getStatus: async () => realSuccessStatus,
+ removeFile: async () => undefined,
+ updateFile: async () => ({ success: true }),
+ uploadFile: async () => ({ id: 'file_guide', url: 'https://app.lobehub.com/f/file_guide' }),
+ ...overrides,
+ } as AIEditDeps;
+ return deps;
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.test.tsx b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.test.tsx
new file mode 100644
index 00000000000..117d3b6d848
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.test.tsx
@@ -0,0 +1,285 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ImageStageContext, type ImageStageValue } from '../../context';
+import { clientToImagePoint } from '../../geometry';
+import { createMockDeps, errorStatus, realProcessingStatus } from './fixtures';
+import AIEditMode from './index';
+import { ERASE_MARK_COLOR } from './request';
+
+const aiInfra = vi.hoisted(() => ({
+ enabledImageModelList: [] as any[],
+}));
+vi.mock('@/store/aiInfra', () => ({
+ aiProviderSelectors: { enabledImageModelList: (s: any) => s.enabledImageModelList },
+ getAiInfraStoreState: () => aiInfra,
+}));
+vi.mock('@/store/global', () => ({
+ useGlobalStore: { getState: () => ({ status: {} }) },
+}));
+
+const fileStore = vi.hoisted(() => ({ refreshFileList: vi.fn() }));
+vi.mock('@/store/file', () => ({
+ fileManagerSelectors: {
+ getFileByChunkTargetId: () => () => ({ id: 'file_src', parentId: 'docs_folder' }),
+ },
+ useFileStore: { getState: () => fileStore },
+}));
+
+const exporter = vi.hoisted(() => ({
+ loadReadableImage: vi.fn(),
+ renderImageToBlob: vi.fn(),
+}));
+vi.mock('../exportImage', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ renderImageToBlob: exporter.renderImageToBlob,
+}));
+vi.mock('./deps', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ loadStageImage: exporter.loadReadableImage,
+}));
+
+const toast = vi.hoisted(() => ({ error: vi.fn(), info: vi.fn(), success: vi.fn() }));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast,
+}));
+
+const EDIT_MODEL = {
+ children: [{ abilities: {}, id: 'gemini-3.1-flash-image:image', parameters: { imageUrls: {} } }],
+ id: 'lobehub',
+ name: 'LobeHub',
+ source: 'builtin',
+};
+
+const RECT = { bottom: 100, height: 100, left: 0, right: 200, top: 0, width: 200, x: 0, y: 0 };
+
+const addVersion = vi.fn();
+
+const renderMode = (operation: 'erase' | 'removeBackground', deps = createMockDeps()) => {
+ const overlay = document.createElement('div');
+ overlay.getBoundingClientRect = () => RECT as DOMRect;
+ document.body.append(overlay);
+ const value: ImageStageValue = {
+ addVersion,
+ fileId: 'file_src',
+ compact: false,
+ fitToScreen: vi.fn(),
+ markup: { comments: [], shapes: [] },
+ name: 'scene.png',
+ naturalSize: { height: 512, width: 768 },
+ overlayElement: overlay,
+ rotation: 0,
+ setBusy: vi.fn(),
+ setMarkup: vi.fn(),
+ setReserve: vi.fn(),
+ toImagePoint: (client) => clientToImagePoint(client, RECT, 0),
+ url: 'https://app.lobehub.com/f/file_src',
+ zoom: 1,
+ };
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <ImageStageContext value={value}>{children}</ImageStageContext>
+ );
+ const onExit = vi.fn();
+ const view = render(<AIEditMode deps={deps} operation={operation} onExit={onExit} />, {
+ wrapper,
+ });
+ return { ...view, onExit, overlay };
+};
+
+/** Skip past one status poll interval of the real pipeline. */
+const nextPoll = () => act(() => vi.advanceTimersByTimeAsync(2100));
+
+beforeEach(() => {
+ vi.useFakeTimers({ shouldAdvanceTime: true });
+ aiInfra.enabledImageModelList = [EDIT_MODEL];
+ exporter.loadReadableImage.mockResolvedValue({ naturalHeight: 512, naturalWidth: 768 });
+ exporter.renderImageToBlob.mockResolvedValue(new Blob(['guide'], { type: 'image/png' }));
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ document.body.innerHTML = '';
+});
+
+describe('AIEditMode — remove background', () => {
+ it('shows progress while generating, then saves a new image and exits', async () => {
+ let finish!: () => void;
+ const gate = new Promise<void>((resolve) => (finish = resolve));
+ const base = createMockDeps();
+ const deps = createMockDeps({
+ getStatus: vi.fn(async (...args: [string, string]) => {
+ await gate;
+ return base.getStatus(...args);
+ }),
+ updateFile: vi.fn(base.updateFile),
+ });
+ const { onExit, overlay } = renderMode('removeBackground', deps);
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.removeBackground.start' }));
+
+ expect(await screen.findByRole('status')).toHaveTextContent('imageViewer.ai.phase.generating');
+ expect(overlay.querySelector('[data-testid="image-ai-progress"]')).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'imageViewer.cancel' })).toBeInTheDocument();
+
+ finish();
+ await nextPoll();
+
+ await waitFor(() => expect(onExit).toHaveBeenCalled());
+ expect(deps.updateFile).toHaveBeenCalledWith(
+ 'file_KWGzzbWzaunM',
+ expect.objectContaining({ name: 'scene-no-bg.png', parentId: 'docs_folder' }),
+ );
+ expect(toast.success).toHaveBeenCalledWith('imageViewer.saved');
+ expect(fileStore.refreshFileList).toHaveBeenCalled();
+ // The result goes on stage as a version next to the original.
+ expect(addVersion).toHaveBeenCalledWith({
+ fileId: 'file_KWGzzbWzaunM',
+ name: 'scene-no-bg.png',
+ operation: 'removeBackground',
+ url: 'https://app.lobehub.com/f/file_KWGzzbWzaunM',
+ });
+ });
+
+ it('shows the failure inline with retry, and keeps the tool open', async () => {
+ const deps = createMockDeps({ getStatus: async () => errorStatus as any });
+ const { onExit } = renderMode('removeBackground', deps);
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.removeBackground.start' }));
+ await nextPoll();
+
+ const alert = await screen.findByRole('alert');
+ expect(alert).toHaveTextContent('imageViewer.ai.error.failed');
+ // The raw provider message is folded into the tooltip, not the status line.
+ expect(alert).toHaveAttribute('title', 'Content blocked by the provider safety filter');
+ expect(screen.getByRole('button', { name: 'imageViewer.retry' })).toBeEnabled();
+ expect(screen.getByRole('button', { name: 'imageViewer.close' })).toBeInTheDocument();
+ expect(onExit).not.toHaveBeenCalled();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(addVersion).not.toHaveBeenCalled();
+ });
+
+ it('stops waiting for a running edit without deleting the server task', async () => {
+ const deleteTopic = vi.fn(async () => undefined);
+ const deps = createMockDeps({
+ deleteTopic,
+ getStatus: async () => realProcessingStatus as any,
+ });
+ const { onExit } = renderMode('removeBackground', deps);
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.removeBackground.start' }));
+ await screen.findByRole('status');
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.cancel' }));
+
+ await waitFor(() => expect(toast.info).toHaveBeenCalledWith('imageViewer.ai.stoppedWaiting'));
+ expect(deleteTopic).not.toHaveBeenCalled();
+ expect(screen.queryByRole('status')).toBeNull();
+ expect(
+ screen.getByRole('button', { name: 'imageViewer.ai.removeBackground.start' }),
+ ).toBeEnabled();
+ expect(onExit).not.toHaveBeenCalled();
+ });
+
+ it('explains when no enabled model can edit images', async () => {
+ aiInfra.enabledImageModelList = [];
+ const createImage = vi.fn();
+ renderMode('removeBackground', createMockDeps({ createImage }));
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.removeBackground.start' }));
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('imageViewer.ai.error.noModel');
+ expect(createImage).not.toHaveBeenCalled();
+ });
+});
+
+describe('AIEditMode — erase', () => {
+ const paint = (canvas: HTMLElement) => {
+ canvas.setPointerCapture = vi.fn();
+ fireEvent.pointerDown(canvas, { button: 0, clientX: 40, clientY: 40, pointerId: 1 });
+ fireEvent.pointerMove(canvas, { clientX: 80, clientY: 60, pointerId: 1 });
+ fireEvent.pointerUp(canvas, { pointerId: 1 });
+ };
+
+ it('requires painting before erasing', () => {
+ renderMode('erase');
+ expect(screen.getByRole('button', { name: 'imageViewer.ai.erase.start' })).toBeDisabled();
+ });
+
+ it('renders the painted region into the guide and submits it', async () => {
+ const base = createMockDeps();
+ const deps = createMockDeps({
+ createImage: vi.fn(base.createImage),
+ uploadFile: vi.fn(base.uploadFile),
+ });
+ const { onExit, overlay } = renderMode('erase', deps);
+
+ paint(overlay.querySelector('[data-testid="image-erase-canvas"]')!);
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.erase.start' }));
+ await waitFor(() => expect(deps.uploadFile).toHaveBeenCalled());
+ await nextPoll();
+
+ await waitFor(() => expect(onExit).toHaveBeenCalled());
+
+ const [, options] = exporter.renderImageToBlob.mock.calls[0];
+ expect(options.shapes).toHaveLength(1);
+ expect(options.shapes[0]).toMatchObject({ color: ERASE_MARK_COLOR, type: 'brush' });
+ expect(options.shapes[0].points[0]).toEqual({ x: 0.2, y: 0.4 });
+ expect(deps.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({ file: expect.objectContaining({ name: 'scene-erase-guide.png' }) }),
+ );
+ expect((deps.createImage as any).mock.calls[0][0].params.imageUrls).toEqual([
+ 'https://app.lobehub.com/f/file_guide',
+ ]);
+ });
+
+ // Regression: rendering the guide happened before the run started, so Start
+ // stayed enabled and a cancel could not stop the job that followed.
+ it('locks Start while the guide renders, and a cancel then submits nothing', async () => {
+ let finishGuide!: (blob: Blob) => void;
+ exporter.renderImageToBlob.mockReturnValue(
+ new Promise<Blob>((resolve) => (finishGuide = resolve)),
+ );
+ const base = createMockDeps();
+ const deps = createMockDeps({
+ createImage: vi.fn(base.createImage),
+ uploadFile: vi.fn(base.uploadFile),
+ });
+ const { overlay } = renderMode('erase', deps);
+
+ paint(overlay.querySelector('[data-testid="image-erase-canvas"]')!);
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.erase.start' }));
+
+ expect(await screen.findByRole('status')).toHaveTextContent('imageViewer.ai.phase.uploading');
+ expect(screen.queryByRole('button', { name: 'imageViewer.ai.erase.start' })).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.cancel' }));
+
+ await act(async () => finishGuide(new Blob(['guide'], { type: 'image/png' })));
+
+ await waitFor(() => expect(toast.info).toHaveBeenCalledWith('imageViewer.ai.cancelled'));
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ expect(deps.createImage).not.toHaveBeenCalled();
+ });
+});
+
+describe('AIEditMode — task still running', () => {
+ it('does not offer Retry when the status of a submitted job is unknown', async () => {
+ const deps = createMockDeps({
+ getStatus: async () => {
+ throw new Error('fetch failed');
+ },
+ });
+ renderMode('removeBackground', deps);
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.ai.removeBackground.start' }));
+ await nextPoll();
+
+ expect(await screen.findByRole('alert')).toHaveTextContent('imageViewer.ai.error.lostTrack');
+ expect(screen.queryByRole('button', { name: 'imageViewer.retry' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'imageViewer.close' })).toBeInTheDocument();
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.tsx b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.tsx
new file mode 100644
index 00000000000..8bc9e44792b
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/index.tsx
@@ -0,0 +1,402 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, keyframes } from 'antd-style';
+import {
+ CircleAlertIcon,
+ EraserIcon,
+ LoaderCircleIcon,
+ RotateCcwIcon,
+ Trash2Icon,
+ Undo2Icon,
+ WandSparklesIcon,
+ XIcon,
+} from 'lucide-react';
+import type { PointerEvent } from 'react';
+import { useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { useImageStage } from '../../context';
+import {
+ type BrushShape,
+ drawBrushSegment,
+ drawShapes,
+ isMeaningfulShape,
+} from '../Annotate/shapes';
+import BarButton from '../BarButton';
+import { renderImageToBlob } from '../exportImage';
+import { toolStyles } from '../styles';
+import { useToolKeys } from '../useToolKeys';
+import { loadStageImage } from './deps';
+import { type AIEditOperation, ERASE_MARK_COLOR } from './request';
+import type { AIEditDeps } from './runAIImageEdit';
+import { useAIImageEdit } from './useAIImageEdit';
+
+/** Brush widths as a fraction of the image's shorter side; erase strokes are broad. */
+export const ERASE_BRUSH_SIZES = { large: 0.07, medium: 0.04, small: 0.02 } as const;
+type BrushSizeKey = keyof typeof ERASE_BRUSH_SIZES;
+/** Smallest first, so the dots grow left to right. */
+const BRUSH_KEYS: BrushSizeKey[] = ['small', 'medium', 'large'];
+
+/** A dot whose size shows the brush size. */
+const BrushDot = ({ index }: { index: number }) => (
+ <span
+ style={{
+ background: 'currentColor',
+ borderRadius: '50%',
+ display: 'block',
+ height: 6 + index * 4,
+ width: 6 + index * 4,
+ }}
+ />
+);
+
+const sweep = keyframes`
+ from { transform: translateX(-100%); }
+ to { transform: translateX(100%); }
+`;
+const spin = keyframes`
+ to { transform: rotate(360deg); }
+`;
+
+const styles = createStaticStyles(({ css }) => ({
+ error: css`
+ overflow: hidden;
+ display: flex;
+ flex-shrink: 1;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+ max-width: 420px;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ color: ${cssVar.colorError};
+ white-space: nowrap;
+ `,
+ mask: css`
+ opacity: 0.5;
+ `,
+ progress: css`
+ pointer-events: none;
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+
+ &::after {
+ content: '';
+
+ position: absolute;
+ inset: 0;
+
+ background: linear-gradient(
+ 90deg,
+ transparent 0%,
+ rgb(255 255 255 / 35%) 50%,
+ transparent 100%
+ );
+
+ animation: ${sweep} 1.6s ease-in-out infinite;
+ }
+ `,
+ spinner: css`
+ animation: ${spin} 1s linear infinite;
+ `,
+ status: css`
+ overflow: hidden;
+ display: flex;
+ flex-shrink: 1;
+ gap: 6px;
+ align-items: center;
+
+ min-width: 0;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+ `,
+}));
+
+interface AIEditModeProps {
+ /** Injected in tests; defaults to the real image generation services. */
+ deps?: AIEditDeps;
+ onExit: () => void;
+ operation: AIEditOperation;
+}
+
+/**
+ * Remove background / erase with an image model. Erase first collects brush
+ * strokes over the region to remove; both submit the image to the generation
+ * pipeline and save the output as a new file, never touching the original.
+ */
+const AIEditMode = ({ deps, onExit, operation }: AIEditModeProps) => {
+ const { t } = useTranslation('file');
+ const { compact, overlayElement, toImagePoint, url } = useImageStage();
+ const { cancel, reset, run, state } = useAIImageEdit(operation, deps);
+ const running = state.status === 'running';
+ const isErase = operation === 'erase';
+
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const [sizeKey, setSizeKey] = useState<BrushSizeKey>('medium');
+ const [strokes, setStrokes] = useState<BrushShape[]>([]);
+ // The stroke being painted; it grows in place and is drawn segment by segment.
+ const draftRef = useRef<BrushShape | null>(null);
+
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!running) return;
+ setNow(Date.now());
+ const timer = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(timer);
+ }, [running]);
+
+ // Keep the mask canvas backing store matched to its displayed size.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!isErase || !canvas || !overlayElement) return;
+ const sync = () => {
+ const ratio = window.devicePixelRatio || 1;
+ canvas.width = Math.max(1, Math.round(overlayElement.clientWidth * ratio));
+ canvas.height = Math.max(1, Math.round(overlayElement.clientHeight * ratio));
+ setStrokes((value) => [...value]);
+ };
+ sync();
+ if (!('ResizeObserver' in window)) return;
+ const observer = new ResizeObserver(sync);
+ observer.observe(overlayElement);
+ return () => observer.disconnect();
+ }, [isErase, overlayElement]);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (!canvas || !ctx) return;
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ // The live stroke lives in the ref (it grows without re-rendering).
+ const live = draftRef.current;
+ drawShapes(ctx, live ? [...strokes, live] : strokes, canvas.width, canvas.height);
+ }, [strokes]);
+
+ const canSubmit = !running && (!isErase || strokes.length > 0);
+
+ const submit = async () => {
+ if (!canSubmit) return;
+ // The guide is rendered inside the run, so Start is locked and Cancel or
+ // leaving the tool abort it before any job is submitted.
+ const prepareGuide = isErase
+ ? async () => renderImageToBlob(await loadStageImage(url), { shapes: strokes })
+ : undefined;
+ const result = await run(prepareGuide);
+ if (result) onExit();
+ };
+
+ const undo = () => setStrokes((value) => value.slice(0, -1));
+
+ useToolKeys({
+ onEnter: () => void submit(),
+ onEscape: running ? cancel : onExit,
+ onUndo: isErase && !running ? undo : undefined,
+ });
+
+ const handlePointerDown = (event: PointerEvent<HTMLCanvasElement>) => {
+ if (event.button !== 0 || running) return;
+ event.stopPropagation();
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ if (state.status === 'error') reset();
+ // The stroke grows in place on later moves, without re-rendering.
+ draftRef.current = {
+ color: ERASE_MARK_COLOR,
+ points: [point, point],
+ size: ERASE_BRUSH_SIZES[sizeKey],
+ type: 'brush',
+ };
+ };
+
+ const handlePointerMove = (event: PointerEvent<HTMLCanvasElement>) => {
+ const value = draftRef.current;
+ if (!value) return;
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ // Grow the stroke in place and paint only the new segment.
+ const last = value.points.at(-1)!;
+ value.points.push(point);
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (canvas && ctx) drawBrushSegment(ctx, value, last, point, canvas.width, canvas.height);
+ };
+
+ const handlePointerUp = () => {
+ const value = draftRef.current;
+ if (value && isMeaningfulShape(value)) setStrokes((list) => [...list, value]);
+ draftRef.current = null;
+ };
+
+ const label = t(`imageViewer.tool.${operation}`);
+
+ const renderStatus = () => {
+ if (state.status === 'running') {
+ const seconds = Math.max(0, Math.round((now - state.startedAt) / 1000));
+ return (
+ <span aria-live={'polite'} className={styles.status} role={'status'}>
+ <LoaderCircleIcon className={styles.spinner} size={14} />
+ {t(`imageViewer.ai.phase.${state.phase}`, { seconds })}
+ </span>
+ );
+ }
+ if (state.status === 'error') {
+ return (
+ // The provider's raw message stays one hover away instead of in the line.
+ <span
+ className={styles.error}
+ role={'alert'}
+ title={state.kind === 'failed' ? state.message : undefined}
+ >
+ <CircleAlertIcon size={14} style={{ flexShrink: 0 }} />
+ {t(
+ state.taskRunning && state.kind !== 'timeout'
+ ? 'imageViewer.ai.error.lostTrack'
+ : `imageViewer.ai.error.${state.kind}`,
+ )}
+ </span>
+ );
+ }
+ return (
+ <span className={toolStyles.hint}>
+ {t(isErase ? 'imageViewer.ai.erase.hint' : 'imageViewer.ai.removeBackground.hint')}
+ </span>
+ );
+ };
+
+ return (
+ <>
+ {overlayElement &&
+ createPortal(
+ <>
+ {isErase && (
+ <canvas
+ aria-label={t('imageViewer.ai.erase.hint')}
+ className={`${toolStyles.overlayFill} ${styles.mask}`}
+ data-testid={'image-erase-canvas'}
+ ref={canvasRef}
+ role={'img'}
+ style={{
+ cursor: running ? 'progress' : 'crosshair',
+ height: '100%',
+ touchAction: 'none',
+ width: '100%',
+ }}
+ onPointerCancel={handlePointerUp}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ />
+ )}
+ {running && <div className={styles.progress} data-testid={'image-ai-progress'} />}
+ </>,
+ overlayElement,
+ )}
+ <div className={toolStyles.dock}>
+ <div aria-label={label} className={toolStyles.bar} role={'toolbar'}>
+ {isErase && !running && (
+ <>
+ {compact ? (
+ <ActionIcon
+ aria-label={t('imageViewer.ai.brushSize')}
+ icon={<BrushDot index={BRUSH_KEYS.indexOf(sizeKey)} />}
+ size={'small'}
+ title={t('imageViewer.ai.brushSize')}
+ onClick={() =>
+ setSizeKey(BRUSH_KEYS[(BRUSH_KEYS.indexOf(sizeKey) + 1) % BRUSH_KEYS.length])
+ }
+ />
+ ) : (
+ <div
+ aria-label={t('imageViewer.ai.brushSize')}
+ role={'group'}
+ style={{ display: 'flex' }}
+ >
+ {BRUSH_KEYS.map((key, index) => (
+ <ActionIcon
+ active={sizeKey === key}
+ aria-label={`${t('imageViewer.ai.brushSize')} ${index + 1}`}
+ aria-pressed={sizeKey === key}
+ icon={<BrushDot index={index} />}
+ key={key}
+ size={'small'}
+ onClick={() => setSizeKey(key)}
+ />
+ ))}
+ </div>
+ )}
+ <ActionIcon
+ aria-label={t('imageViewer.annotate.undo')}
+ disabled={strokes.length === 0}
+ icon={Undo2Icon}
+ size={'small'}
+ title={t('imageViewer.annotate.undo')}
+ onClick={undo}
+ />
+ <ActionIcon
+ aria-label={t('imageViewer.annotate.clear')}
+ disabled={strokes.length === 0}
+ icon={Trash2Icon}
+ size={'small'}
+ title={t('imageViewer.annotate.clear')}
+ onClick={() => setStrokes([])}
+ />
+ <span className={toolStyles.divider} />
+ </>
+ )}
+ {renderStatus()}
+ <span className={toolStyles.divider} />
+ {running ? (
+ <BarButton icon={XIcon} label={t('imageViewer.cancel')} onClick={cancel} />
+ ) : (
+ <>
+ <BarButton
+ icon={XIcon}
+ label={state.status === 'error' ? t('imageViewer.close') : t('imageViewer.cancel')}
+ onClick={onExit}
+ />
+ {/* A job that may still be running must not be submitted twice. */}
+ {!(state.status === 'error' && state.taskRunning) && (
+ <BarButton
+ disabled={!canSubmit}
+ type={'primary'}
+ icon={
+ state.status === 'error'
+ ? RotateCcwIcon
+ : isErase
+ ? EraserIcon
+ : WandSparklesIcon
+ }
+ label={
+ state.status === 'error'
+ ? t('imageViewer.retry')
+ : t(
+ isErase
+ ? 'imageViewer.ai.erase.start'
+ : 'imageViewer.ai.removeBackground.start',
+ )
+ }
+ title={
+ isErase && strokes.length === 0 ? t('imageViewer.ai.erase.empty') : undefined
+ }
+ onClick={() => void submit()}
+ />
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </>
+ );
+};
+
+export default AIEditMode;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/request.test.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/request.test.ts
new file mode 100644
index 00000000000..d398d63c5cb
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/request.test.ts
@@ -0,0 +1,106 @@
+import { describe, expect, it } from 'vitest';
+
+import type { EnabledProviderWithModels } from '@/types/aiProvider';
+
+import { AI_EDIT_PROMPTS, buildAIEditRequest, resolveAIEditModel } from './request';
+
+const card = (id: string, parameters?: Record<string, unknown>) =>
+ ({ abilities: {}, id, parameters }) as EnabledProviderWithModels['children'][number];
+
+const providers = (list: [string, ReturnType<typeof card>[]][]): EnabledProviderWithModels[] =>
+ list.map(([id, children]) => ({ children, id, name: id, source: 'builtin' }) as any);
+
+describe('resolveAIEditModel', () => {
+ const enabled = providers([
+ [
+ 'lobehub',
+ [
+ card('text-only', { prompt: { default: '' } }),
+ card('gemini-3.1-flash-image:image', { imageUrls: { default: [] }, prompt: {} }),
+ ],
+ ],
+ ['fal', [card('flux-kontext', { imageUrl: { default: null }, prompt: {} })]],
+ ]);
+
+ it('prefers the last selected model when it accepts a reference image', () => {
+ expect(resolveAIEditModel(enabled, { model: 'flux-kontext', provider: 'fal' })).toEqual({
+ model: 'flux-kontext',
+ provider: 'fal',
+ referenceParam: 'imageUrl',
+ });
+ });
+
+ it('skips a last selected model that cannot take a reference image', () => {
+ expect(resolveAIEditModel(enabled, { model: 'text-only', provider: 'lobehub' })).toEqual({
+ model: 'gemini-3.1-flash-image:image',
+ provider: 'lobehub',
+ referenceParam: 'imageUrls',
+ });
+ });
+
+ it('keeps the reference image size limit the model declares', () => {
+ const limited = providers([
+ ['openai', [card('gpt-image-1', { imageUrls: { default: [], maxFileSize: 5_242_880 } })]],
+ ]);
+ expect(resolveAIEditModel(limited)).toEqual({
+ maxFileSize: 5_242_880,
+ model: 'gpt-image-1',
+ provider: 'openai',
+ referenceParam: 'imageUrls',
+ });
+ });
+
+ it('falls back to any editable model', () => {
+ expect(
+ resolveAIEditModel(providers([['fal', [card('flux-kontext', { imageUrl: {} })]]])),
+ ).toMatchObject({ model: 'flux-kontext', provider: 'fal' });
+ });
+
+ it('returns undefined when no enabled model can edit', () => {
+ expect(resolveAIEditModel(providers([['x', [card('t2i', { prompt: {} })]]]))).toBeUndefined();
+ expect(resolveAIEditModel([])).toBeUndefined();
+ });
+});
+
+describe('buildAIEditRequest', () => {
+ it('sends the image as `imageUrls` with the operation prompt', () => {
+ expect(
+ buildAIEditRequest({
+ generationTopicId: 'gt_1',
+ imageUrl: 'https://app.lobehub.com/f/file_src',
+ model: {
+ model: 'gemini-3.1-flash-image:image',
+ provider: 'lobehub',
+ referenceParam: 'imageUrls',
+ },
+ operation: 'removeBackground',
+ }),
+ ).toEqual({
+ generationTopicId: 'gt_1',
+ imageNum: 1,
+ model: 'gemini-3.1-flash-image:image',
+ params: {
+ imageUrls: ['https://app.lobehub.com/f/file_src'],
+ prompt: AI_EDIT_PROMPTS.removeBackground,
+ },
+ provider: 'lobehub',
+ });
+ });
+
+ it('uses `imageUrl` for single-reference models', () => {
+ const request = buildAIEditRequest({
+ generationTopicId: 'gt_1',
+ imageUrl: 'https://guide.png',
+ model: { model: 'flux-kontext', provider: 'fal', referenceParam: 'imageUrl' },
+ operation: 'erase',
+ });
+ expect(request.params).toEqual({
+ imageUrl: 'https://guide.png',
+ prompt: AI_EDIT_PROMPTS.erase,
+ });
+ });
+
+ it('describes the erase mark color in the erase prompt', () => {
+ expect(AI_EDIT_PROMPTS.erase).toContain('#FF00FF');
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/request.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/request.ts
new file mode 100644
index 00000000000..83a29b46097
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/request.ts
@@ -0,0 +1,101 @@
+import {
+ DEFAULT_AI_IMAGE_MODEL,
+ DEFAULT_AI_IMAGE_PROVIDER,
+} from '@/store/image/slices/generationConfig/initialState';
+import type { EnabledProviderWithModels } from '@/types/aiProvider';
+
+export type AIEditOperation = 'erase' | 'removeBackground';
+
+/** Paint color that marks the erase region on the guide image sent to the model. */
+export const ERASE_MARK_COLOR = '#ff00ff';
+
+export const AI_EDIT_PROMPTS: Record<AIEditOperation, string> = {
+ erase:
+ 'The areas painted in solid magenta (#FF00FF) mark content to erase. Remove everything under the magenta paint and fill those areas so they blend seamlessly with the surrounding image, as if the erased content was never there. Keep every other part of the image exactly as it is, keep the same framing and aspect ratio, and make sure no magenta remains in the result.',
+ removeBackground:
+ 'Remove the background of this image. Keep the main subject exactly as it is — same position, size, colors and details — and place it on a single flat, uniform chroma-key green (#00FF00) backdrop with no gradient, shadow, texture or reflection. Keep the same framing and aspect ratio and do not add anything else.',
+};
+
+export interface AIEditModel {
+ /** Largest reference image the model accepts, in bytes, when it declares one. */
+ maxFileSize?: number;
+ model: string;
+ provider: string;
+ /** Which reference-image parameter the model reads. */
+ referenceParam: 'imageUrl' | 'imageUrls';
+}
+
+const referenceParamOf = (
+ parameters: Record<string, unknown> | undefined,
+): AIEditModel['referenceParam'] | undefined => {
+ if (!parameters) return;
+ if ('imageUrls' in parameters) return 'imageUrls';
+ if ('imageUrl' in parameters) return 'imageUrl';
+};
+
+const findEditable = (
+ providers: EnabledProviderWithModels[],
+ provider: string | undefined,
+ model: string | undefined,
+): AIEditModel | undefined => {
+ for (const item of providers) {
+ if (provider && item.id !== provider) continue;
+ for (const card of item.children) {
+ if (model && card.id !== model) continue;
+ const parameters = card.parameters as Record<string, unknown> | undefined;
+ const referenceParam = referenceParamOf(parameters);
+ if (!referenceParam) continue;
+ const maxFileSize = (parameters?.[referenceParam] as { maxFileSize?: unknown } | undefined)
+ ?.maxFileSize;
+ return {
+ ...(typeof maxFileSize === 'number' ? { maxFileSize } : {}),
+ model: card.id,
+ provider: item.id,
+ referenceParam,
+ };
+ }
+ }
+};
+
+/**
+ * Pick an enabled image model that accepts a reference image, in the same order
+ * the image page initializes: the user's last pick, then the default model
+ * (default provider first), then any model that can edit.
+ */
+export const resolveAIEditModel = (
+ providers: EnabledProviderWithModels[],
+ lastSelected?: { model?: string; provider?: string },
+): AIEditModel | undefined => {
+ if (lastSelected?.model && lastSelected.provider) {
+ const picked = findEditable(providers, lastSelected.provider, lastSelected.model);
+ if (picked) return picked;
+ }
+
+ return (
+ findEditable(providers, DEFAULT_AI_IMAGE_PROVIDER, DEFAULT_AI_IMAGE_MODEL) ??
+ findEditable(providers, undefined, DEFAULT_AI_IMAGE_MODEL) ??
+ findEditable(providers, undefined, undefined)
+ );
+};
+
+/** Payload for `image.createImage`: one image, edited from a single reference. */
+export const buildAIEditRequest = ({
+ generationTopicId,
+ imageUrl,
+ model,
+ operation,
+}: {
+ generationTopicId: string;
+ imageUrl: string;
+ model: AIEditModel;
+ operation: AIEditOperation;
+}) => ({
+ generationTopicId,
+ imageNum: 1,
+ model: model.model,
+ params: {
+ prompt: AI_EDIT_PROMPTS[operation],
+ ...(model.referenceParam === 'imageUrls' ? { imageUrls: [imageUrl] } : { imageUrl }),
+ },
+ provider: model.provider,
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/runAIImageEdit.test.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/runAIImageEdit.test.ts
new file mode 100644
index 00000000000..ebd8a16abb1
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/runAIImageEdit.test.ts
@@ -0,0 +1,654 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ createMockDeps,
+ errorStatus,
+ realCreateImageResult,
+ realProcessingStatus,
+ realResultFileMetadata,
+ realSuccessStatus,
+} from './fixtures';
+import { AI_EDIT_PROMPTS } from './request';
+import { AIImageEditError, runAIImageEdit } from './runAIImageEdit';
+
+const MODEL = {
+ model: 'gemini-3.1-flash-image:image',
+ provider: 'lobehub',
+ referenceParam: 'imageUrls' as const,
+};
+const SOURCE = {
+ fileId: 'file_5EPW42StH4Bd',
+ name: 'scene.png',
+ parentId: 'docs_folder',
+ url: 'https://app.lobehub.com/f/file_5EPW42StH4Bd',
+};
+
+const spyDeps = (overrides = {}) => {
+ const base = createMockDeps(overrides);
+ return Object.fromEntries(
+ Object.entries(base).map(([key, fn]) => [key, vi.fn(fn as any)]),
+ ) as unknown as { [K in keyof typeof base]: ReturnType<typeof vi.fn> } & typeof base;
+};
+
+/** No call may write to, move, or delete the source file. */
+const expectSourceUntouched = (deps: ReturnType<typeof spyDeps>) => {
+ for (const call of deps.updateFile.mock.calls) expect(call[0]).not.toBe(SOURCE.fileId);
+ for (const call of deps.removeFile.mock.calls) expect(call[0]).not.toBe(SOURCE.fileId);
+ for (const call of deps.uploadFile.mock.calls) expect(call[0].file.name).not.toBe(SOURCE.name);
+};
+
+const run = (deps: ReturnType<typeof spyDeps>, extra: Record<string, unknown> = {}) =>
+ runAIImageEdit({
+ deps,
+ model: MODEL,
+ operation: 'removeBackground',
+ pollInterval: 1,
+ source: SOURCE,
+ topicTitle: 'Remove background · scene.png',
+ ...extra,
+ });
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('runAIImageEdit', () => {
+ it('submits the original image to the generation pipeline with the remove-background prompt', async () => {
+ const deps = spyDeps();
+ await run(deps);
+
+ expect(deps.createTopic).toHaveBeenCalledWith('Remove background · scene.png', undefined);
+ expect(deps.createImage).toHaveBeenCalledWith({
+ generationTopicId: 'gt_6p9nBZERtyWe',
+ imageNum: 1,
+ model: 'gemini-3.1-flash-image:image',
+ params: { imageUrls: [SOURCE.url], prompt: AI_EDIT_PROMPTS.removeBackground },
+ provider: 'lobehub',
+ });
+ expect(deps.getStatus).toHaveBeenCalledWith(
+ 'gen_IUVYApnU4NYX',
+ '0f070379-d3ef-4038-9cfb-c88764b63399',
+ );
+ // Remove background reads the stored file directly: nothing is uploaded.
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ });
+
+ it('saves the result as a new file next to the original and never touches the original', async () => {
+ const deps = spyDeps();
+ const phases: string[] = [];
+ const result = await run(deps, { onPhase: (phase: string) => phases.push(phase) });
+
+ expect(result).toEqual({
+ fileId: 'file_KWGzzbWzaunM',
+ height: 843,
+ libraryFailed: false,
+ name: 'scene-no-bg.png',
+ url: 'https://app.lobehub.com/f/file_KWGzzbWzaunM',
+ width: 1264,
+ });
+ expect(result.fileId).not.toBe(SOURCE.fileId);
+ expect(deps.updateFile).toHaveBeenCalledTimes(1);
+ expect(deps.updateFile).toHaveBeenCalledWith('file_KWGzzbWzaunM', {
+ metadata: {
+ ...realResultFileMetadata,
+ derivedFrom: { fileId: SOURCE.fileId, operation: 'removeBackground' },
+ },
+ name: 'scene-no-bg.png',
+ parentId: 'docs_folder',
+ });
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ expect(phases).toEqual(['generating', 'saving']);
+ expectSourceUntouched(deps);
+ });
+
+ // Regression: remove background saved the model's opaque output as is.
+ it('saves the keyed-out transparent PNG for remove background', async () => {
+ const transparent = new File(['png'], 'scene-no-bg.png', { type: 'image/png' });
+ const deps = spyDeps({
+ cutOutBackground: async () => transparent,
+ uploadFile: async () => ({ id: 'file_cutout', url: 'https://app.lobehub.com/f/file_cutout' }),
+ });
+
+ const result = await run(deps);
+
+ expect(deps.cutOutBackground).toHaveBeenCalledWith(
+ 'https://app.lobehub.com/f/file_KWGzzbWzaunM',
+ 'scene-no-bg.png',
+ );
+ const upload = deps.uploadFile.mock.calls[0][0];
+ expect(upload.file).toBe(transparent);
+ expect(upload.metadata).toEqual({
+ derivedFrom: { fileId: SOURCE.fileId, operation: 'removeBackground' },
+ });
+ expect(upload.parentId).toBe('docs_folder');
+ expect(result.fileId).toBe('file_cutout');
+ // The generation's own file stays in its topic.
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ expectSourceUntouched(deps);
+ });
+
+ it('asks the model for a flat backdrop it can key out', () => {
+ expect(AI_EDIT_PROMPTS.removeBackground).toContain('#00FF00');
+ });
+
+ it('files the result in the original folder even when the viewer does not know it', async () => {
+ const deps = spyDeps();
+ await run(deps, { source: { ...SOURCE, parentId: undefined } });
+
+ expect(deps.getFile).toHaveBeenCalledWith(SOURCE.fileId);
+ expect(deps.updateFile.mock.calls[0][1].parentId).toBe('docs_folder');
+ expectSourceUntouched(deps);
+ });
+
+ it('adds the result to the library the original is filed in', async () => {
+ const deps = spyDeps({
+ getFile: async (id: string) =>
+ id === SOURCE.fileId
+ ? { knowledgeBaseIds: ['kb_photos'], metadata: {}, parentId: 'docs_folder' }
+ : { metadata: realResultFileMetadata, parentId: null },
+ });
+ await run(deps);
+
+ expect(deps.addToKnowledgeBase).toHaveBeenCalledWith('kb_photos', ['file_KWGzzbWzaunM']);
+ expect(deps.addToKnowledgeBase).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports a failed library link without failing the saved edit', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+ const deps = spyDeps({
+ addToKnowledgeBase: async () => {
+ throw new Error('forbidden');
+ },
+ getFile: async (id: string) =>
+ id === SOURCE.fileId
+ ? { knowledgeBaseIds: ['kb_1'], parentId: 'docs_folder' }
+ : { metadata: realResultFileMetadata, parentId: null },
+ });
+
+ const result = await run(deps);
+
+ expect(result.libraryFailed).toBe(true);
+ expect(result.fileId).toBe('file_KWGzzbWzaunM');
+ });
+
+ it('does not touch libraries when the original is in none', async () => {
+ const deps = spyDeps();
+ await run(deps);
+ expect(deps.addToKnowledgeBase).not.toHaveBeenCalled();
+ });
+
+ it('polls until the task finishes', async () => {
+ const getStatus = vi
+ .fn()
+ .mockResolvedValueOnce(realProcessingStatus)
+ .mockResolvedValueOnce(realProcessingStatus)
+ .mockResolvedValueOnce(realSuccessStatus);
+ const deps = spyDeps({ getStatus });
+ await run(deps);
+ expect(getStatus).toHaveBeenCalledTimes(3);
+ });
+
+ it('erase uploads the painted guide, edits it, and cleans the guide up', async () => {
+ const deps = spyDeps();
+ const guide = new Blob(['png'], { type: 'image/png' });
+ const phases: string[] = [];
+ const result = await run(deps, {
+ guide,
+ onPhase: (phase: string) => phases.push(phase),
+ operation: 'erase',
+ topicTitle: 'Erase · scene.png',
+ });
+
+ const uploaded = deps.uploadFile.mock.calls[0][0];
+ expect(uploaded.file.name).toBe('scene-erase-guide.png');
+ expect(uploaded.file.type).toBe('image/png');
+ expect(deps.createImage.mock.calls[0][0].params).toEqual({
+ imageUrls: ['https://app.lobehub.com/f/file_guide'],
+ prompt: AI_EDIT_PROMPTS.erase,
+ });
+ expect(deps.removeFile).toHaveBeenCalledWith('file_guide');
+ expect(result.name).toBe('scene-erased.png');
+ expect(deps.updateFile.mock.calls[0][1].metadata.derivedFrom).toEqual({
+ fileId: SOURCE.fileId,
+ operation: 'erase',
+ });
+ expect(phases).toEqual(['uploading', 'generating', 'saving']);
+ expectSourceUntouched(deps);
+ });
+
+ it('fails with the task error, keeps its record and saves nothing', async () => {
+ const deps = spyDeps({ getStatus: async () => errorStatus });
+ const error = await run(deps, { guide: new Blob(['x']), operation: 'erase' }).catch((e) => e);
+
+ expect(error).toBeInstanceOf(AIImageEditError);
+ expect(error.kind).toBe('failed');
+ expect(error.message).toBe('Content blocked by the provider safety filter');
+ // The failed generation stays under Image generation, like any other run.
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ expect(deps.removeFile).toHaveBeenCalledWith('file_guide');
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ expectSourceUntouched(deps);
+ });
+
+ it('reports a request that is rejected up front', async () => {
+ const deps = spyDeps({
+ createImage: async () => {
+ // Shape of a TRPCClientError for a 4xx answer.
+ throw Object.assign(new Error('Insufficient budget'), { data: { httpStatus: 403 } });
+ },
+ });
+ await expect(run(deps)).rejects.toMatchObject({
+ kind: 'failed',
+ message: 'Insufficient budget',
+ taskRunning: false,
+ });
+ expect(deps.deleteTopic).toHaveBeenCalledWith('gt_6p9nBZERtyWe');
+ });
+
+ // Regression: the server starts the task before answering, so a lost
+ // response must not delete the topic and input of a job that may be running.
+ it('keeps the topic and guide when the create response is lost', async () => {
+ const deps = spyDeps({
+ createImage: async () => {
+ throw new TypeError('Failed to fetch');
+ },
+ });
+ await expect(
+ run(deps, { guide: new Blob(['png'], { type: 'image/png' }), operation: 'erase' }),
+ ).rejects.toMatchObject({ kind: 'failed', taskRunning: true });
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ expect(deps.removeFile).not.toHaveBeenCalled();
+ });
+
+ it('treats a batch without a task as a failure', async () => {
+ const deps = spyDeps({
+ createImage: async () => ({ ...realCreateImageResult, data: { generations: [] } }),
+ });
+ await expect(run(deps)).rejects.toMatchObject({ kind: 'failed' });
+ });
+
+ it('reports success without an asset as no result', async () => {
+ const deps = spyDeps({
+ getStatus: async () => ({
+ ...realSuccessStatus,
+ generation: { ...realSuccessStatus.generation, asset: null },
+ }),
+ });
+ await expect(run(deps)).rejects.toMatchObject({ kind: 'noResult' });
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ });
+
+ it('cancels while generating: stops waiting but keeps the running task and its topic', async () => {
+ const controller = new AbortController();
+ const getStatus = vi.fn(async () => {
+ controller.abort();
+ return realProcessingStatus;
+ });
+ const deps = spyDeps({ getStatus });
+
+ const error = await run(deps, { pollInterval: 5, signal: controller.signal }).catch((e) => e);
+
+ expect(error).toBeInstanceOf(AIImageEditError);
+ expect(error.kind).toBe('cancelled');
+ expect(error.taskRunning).toBe(true);
+ expect(getStatus).toHaveBeenCalledTimes(1);
+ // The server task cannot be aborted; deleting its topic would orphan its result.
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ expectSourceUntouched(deps);
+ });
+
+ it('keeps the erase guide for a task that is still running', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({
+ getStatus: async () => {
+ controller.abort();
+ return realProcessingStatus;
+ },
+ });
+
+ await expect(
+ run(deps, {
+ guide: new Blob(['png'], { type: 'image/png' }),
+ operation: 'erase',
+ signal: controller.signal,
+ }),
+ ).rejects.toMatchObject({ kind: 'cancelled', taskRunning: true });
+ expect(deps.removeFile).not.toHaveBeenCalled();
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ });
+
+ // Regression: nothing removed the guide of an abandoned task once it settled.
+ it('removes the erase guide once an abandoned task settles', async () => {
+ const controller = new AbortController();
+ let polls = 0;
+ const deps = spyDeps({
+ getStatus: async () => {
+ polls += 1;
+ if (polls === 1) {
+ controller.abort();
+ return realProcessingStatus;
+ }
+ return polls < 3 ? realProcessingStatus : realSuccessStatus;
+ },
+ });
+
+ await expect(
+ run(deps, {
+ guide: new Blob(['png'], { type: 'image/png' }),
+ operation: 'erase',
+ signal: controller.signal,
+ }),
+ ).rejects.toMatchObject({ kind: 'cancelled', taskRunning: true });
+ expect(deps.removeFile).not.toHaveBeenCalled();
+
+ await vi.waitFor(() => expect(deps.removeFile).toHaveBeenCalledWith('file_guide'));
+ // The result itself is left in the generation topic.
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ });
+
+ it('cleans up the topic when cancelled before the task is submitted', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({
+ createTopic: async () => {
+ controller.abort();
+ return 'gt_6p9nBZERtyWe';
+ },
+ });
+
+ await expect(run(deps, { signal: controller.signal })).rejects.toMatchObject({
+ kind: 'cancelled',
+ taskRunning: false,
+ });
+ expect(deps.createImage).not.toHaveBeenCalled();
+ await vi.waitFor(() => expect(deps.deleteTopic).toHaveBeenCalledWith('gt_6p9nBZERtyWe'));
+ });
+
+ // Regression: deleting the topic of a finished run removed the stored asset
+ // while its file row survived, leaving a file without bytes.
+ it('leaves a result that arrives after cancel in its generation topic', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({
+ getStatus: async () => {
+ controller.abort();
+ return realSuccessStatus;
+ },
+ });
+ await expect(run(deps, { signal: controller.signal })).rejects.toMatchObject({
+ kind: 'cancelled',
+ });
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ });
+
+ it('keeps a finished result when saving it beside the original fails', async () => {
+ const deps = spyDeps({
+ updateFile: async () => {
+ throw new Error('network');
+ },
+ });
+ await expect(run(deps)).rejects.toMatchObject({ kind: 'failed' });
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ });
+
+ it('prefers the folder reported by the server over a stale client one', async () => {
+ const deps = spyDeps();
+ await run(deps, { source: { ...SOURCE, parentId: 'docs_stale' } });
+
+ expect(deps.updateFile.mock.calls[0][1].parentId).toBe('docs_folder');
+ });
+
+ it('treats a failed status request as a task that may still be running', async () => {
+ const deps = spyDeps({
+ getStatus: async () => {
+ throw new Error('fetch failed');
+ },
+ });
+
+ await expect(run(deps)).rejects.toMatchObject({ kind: 'failed', taskRunning: true });
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ });
+
+ it('gives the generation topic the original file visibility', async () => {
+ const deps = spyDeps({
+ getFile: async (id: string) =>
+ id === SOURCE.fileId
+ ? { knowledgeBaseIds: [], parentId: 'docs_folder', visibility: 'public' as const }
+ : { metadata: realResultFileMetadata, parentId: null },
+ });
+
+ await run(deps);
+
+ expect(deps.createTopic).toHaveBeenCalledWith('Remove background · scene.png', 'public');
+ });
+
+ it('does not submit anything when cancelled before starting', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const deps = spyDeps();
+
+ await expect(run(deps, { signal: controller.signal })).rejects.toMatchObject({
+ kind: 'cancelled',
+ taskRunning: false,
+ });
+ expect(deps.createTopic).not.toHaveBeenCalled();
+ expect(deps.createImage).not.toHaveBeenCalled();
+ });
+
+ // Regression: a hung status request kept the tool locked past cancel and the deadline.
+ it('cancels while a status request hangs', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({ getStatus: () => new Promise<never>(() => {}) });
+
+ const pending = run(deps, { signal: controller.signal });
+ setTimeout(() => controller.abort(), 20);
+
+ await expect(pending).rejects.toMatchObject({ kind: 'cancelled', taskRunning: true });
+ });
+
+ // Regression: a stalled create call ignored Cancel and the deadline.
+ it('cancels while the create call hangs, treating the task as possibly started', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({ createImage: () => new Promise<never>(() => {}) });
+
+ const pending = run(deps, { signal: controller.signal });
+ setTimeout(() => controller.abort(), 20);
+
+ await expect(pending).rejects.toMatchObject({ kind: 'cancelled', taskRunning: true });
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ });
+
+ // Regression: a failing status endpoint was polled every interval for the
+ // whole watch window.
+ it('backs off the guide-cleanup watch while status requests fail', async () => {
+ const controller = new AbortController();
+ let calls = 0;
+ const deps = spyDeps({
+ getStatus: async () => {
+ calls += 1;
+ if (calls === 1) {
+ controller.abort();
+ return realProcessingStatus;
+ }
+ throw new Error('outage');
+ },
+ });
+
+ await run(deps, {
+ guide: new Blob(['png'], { type: 'image/png' }),
+ operation: 'erase',
+ pollInterval: 2,
+ settleWatch: 200,
+ signal: controller.signal,
+ }).catch(() => undefined);
+ await new Promise((resolve) => setTimeout(resolve, 250));
+
+ // Doubling from 2ms within 200ms allows about 7 tries, not ~100.
+ expect(calls).toBeLessThan(12);
+ expect(deps.removeFile).not.toHaveBeenCalled();
+ });
+
+ // Regression: steps before submitting (location lookup, guide upload, topic)
+ // were not raced against Cancel, so a hung one kept the tool locked.
+ it('cancels while a pre-submit step hangs, with nothing submitted', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({ createTopic: () => new Promise<never>(() => {}) });
+
+ const pending = run(deps, { signal: controller.signal });
+ setTimeout(() => controller.abort(), 20);
+
+ await expect(pending).rejects.toMatchObject({ kind: 'cancelled', taskRunning: false });
+ expect(deps.createImage).not.toHaveBeenCalled();
+ });
+
+ // Regression: the save steps after a successful generation ignored Cancel.
+ it('cancels while saving the result hangs', async () => {
+ const controller = new AbortController();
+ const deps = spyDeps({ updateFile: () => new Promise<never>(() => {}) });
+
+ const pending = run(deps, { signal: controller.signal });
+ await vi.waitFor(() => expect(deps.updateFile).toHaveBeenCalled());
+ controller.abort();
+
+ await expect(pending).rejects.toMatchObject({ kind: 'cancelled', taskRunning: false });
+ });
+
+ // Regression: a guide upload that finished after Cancel was never removed.
+ it('removes an erase guide whose upload lands after Cancel', async () => {
+ const controller = new AbortController();
+ let finishUpload!: (value: { id: string; url: string }) => void;
+ const deps = spyDeps({
+ uploadFile: () =>
+ new Promise<{ id: string; url: string }>((resolve) => (finishUpload = resolve)),
+ });
+
+ const pending = run(deps, {
+ guide: new Blob(['png'], { type: 'image/png' }),
+ operation: 'erase',
+ signal: controller.signal,
+ });
+ await vi.waitFor(() => expect(deps.uploadFile).toHaveBeenCalled());
+ controller.abort();
+ await expect(pending).rejects.toMatchObject({ kind: 'cancelled', taskRunning: false });
+
+ finishUpload({ id: 'file_late_guide', url: 'https://app.lobehub.com/f/file_late_guide' });
+ await vi.waitFor(() => expect(deps.removeFile).toHaveBeenCalledWith('file_late_guide'));
+ expect(deps.createImage).not.toHaveBeenCalled();
+ });
+
+ // Regression: images over the model's reference limit were submitted as
+ // tasks the provider then rejected.
+ it('refuses an original larger than the model accepts, before submitting', async () => {
+ const deps = spyDeps({
+ getFile: async () => ({ knowledgeBaseIds: [], parentId: 'docs_folder', size: 6_000_000 }),
+ });
+
+ await expect(run(deps, { model: { ...MODEL, maxFileSize: 5_242_880 } })).rejects.toMatchObject({
+ kind: 'tooLarge',
+ taskRunning: false,
+ });
+ expect(deps.createTopic).not.toHaveBeenCalled();
+ expect(deps.createImage).not.toHaveBeenCalled();
+ });
+
+ it('refuses an erase guide larger than the model accepts', async () => {
+ const deps = spyDeps();
+
+ await expect(
+ run(deps, {
+ guide: new Blob([new Uint8Array(2048)], { type: 'image/png' }),
+ model: { ...MODEL, maxFileSize: 1024 },
+ operation: 'erase',
+ }),
+ ).rejects.toMatchObject({ kind: 'tooLarge' });
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ });
+
+ it('times out while a status request hangs', async () => {
+ const deps = spyDeps({ getStatus: () => new Promise<never>(() => {}) });
+
+ await expect(run(deps, { timeout: 20 })).rejects.toMatchObject({
+ kind: 'timeout',
+ taskRunning: true,
+ });
+ });
+
+ it('stops waiting at the timeout and leaves the running task alone', async () => {
+ const deps = spyDeps({ getStatus: async () => realProcessingStatus });
+ await expect(run(deps, { timeout: 5 })).rejects.toMatchObject({
+ kind: 'timeout',
+ taskRunning: true,
+ });
+ expect(deps.deleteTopic).not.toHaveBeenCalled();
+ });
+
+ // Regression: an older server omits `fileId`, but the `/f/:id` asset URL
+ // still names the file. Fetching the proxy would fail CORS on its redirect.
+ it('uses the file behind a proxy asset URL when the server does not report the file', async () => {
+ const fetchSpy = vi.spyOn(globalThis, 'fetch');
+ const deps = spyDeps({
+ getStatus: async () => ({
+ ...realSuccessStatus,
+ generation: { ...realSuccessStatus.generation, fileId: undefined },
+ }),
+ });
+
+ const result = await run(deps);
+
+ expect(fetchSpy).not.toHaveBeenCalled();
+ expect(deps.uploadFile).not.toHaveBeenCalled();
+ expect(deps.updateFile.mock.calls[0][0]).toBe('file_KWGzzbWzaunM');
+ expect(result.fileId).toBe('file_KWGzzbWzaunM');
+ });
+
+ it('copies the asset into a new file when the server does not report the file', async () => {
+ const blob = new Blob(['png'], { type: 'image/png' });
+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(blob, { status: 200 }));
+ const deps = spyDeps({
+ getStatus: async () => ({
+ ...realSuccessStatus,
+ generation: {
+ ...realSuccessStatus.generation,
+ asset: {
+ ...realSuccessStatus.generation.asset,
+ url: 'https://s3.example.com/result.png',
+ },
+ fileId: undefined,
+ },
+ }),
+ uploadFile: async () => ({ id: 'file_copy', url: 'https://app.lobehub.com/f/file_copy' }),
+ });
+
+ const result = await run(deps);
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ 'https://s3.example.com/result.png',
+ expect.anything(),
+ );
+ const uploaded = deps.uploadFile.mock.calls[0][0];
+ expect(uploaded.file.name).toBe('scene-no-bg.png');
+ expect(uploaded.parentId).toBe('docs_folder');
+ expect(uploaded.metadata).toEqual({
+ derivedFrom: { fileId: SOURCE.fileId, operation: 'removeBackground' },
+ });
+ expect(result.fileId).toBe('file_copy');
+ expect(deps.updateFile).not.toHaveBeenCalled();
+ expectSourceUntouched(deps);
+ });
+
+ it('never lets cleanup failures mask the outcome', async () => {
+ const deps = spyDeps({
+ createImage: async () => {
+ throw Object.assign(new Error('Bad request'), { data: { httpStatus: 400 } });
+ },
+ deleteTopic: async () => {
+ throw new Error('network');
+ },
+ });
+ await expect(run(deps)).rejects.toMatchObject({ kind: 'failed' });
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/runAIImageEdit.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/runAIImageEdit.ts
new file mode 100644
index 00000000000..7ff4a150e5b
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/runAIImageEdit.ts
@@ -0,0 +1,442 @@
+import type { AsyncTaskError, Generation } from '@lobechat/types';
+import { AsyncTaskStatus } from '@lobechat/types';
+
+import {
+ buildDerivedFileMetadata,
+ buildDerivedFileName,
+ DERIVED_FILE_SUFFIX,
+} from '../../geometry';
+import { fileIdFromProxyUrl } from '../exportImage';
+import { fileIntoLibraries } from '../saveDerivedFile';
+import { type AIEditModel, type AIEditOperation, buildAIEditRequest } from './request';
+
+export type AIEditErrorKind =
+ 'cancelled' | 'failed' | 'noModel' | 'noResult' | 'timeout' | 'tooLarge';
+
+export class AIImageEditError extends Error {
+ kind: AIEditErrorKind;
+ /**
+ * The server task was submitted and had not finished when the client stopped
+ * waiting. Its result still lands in the generation topic.
+ */
+ taskRunning: boolean;
+
+ constructor(
+ kind: AIEditErrorKind,
+ message?: string,
+ cause?: unknown,
+ { taskRunning = false }: { taskRunning?: boolean } = {},
+ ) {
+ super(message || kind);
+ this.name = 'AIImageEditError';
+ this.kind = kind;
+ this.cause = cause;
+ this.taskRunning = taskRunning;
+ }
+}
+
+export type AIEditPhase = 'uploading' | 'generating' | 'saving';
+
+interface CreateImageResult {
+ data?: { generations?: { asyncTaskId?: string | null; id?: string }[] };
+ success?: boolean;
+}
+
+interface GenerationStatusResult {
+ error: AsyncTaskError | null;
+ generation: Generation | null;
+ status: AsyncTaskStatus | string;
+}
+
+/** Everything the edit talks to, injected so the flow is testable without a network. */
+export interface AIEditDeps {
+ /** File the result into the same library as the original. */
+ addToKnowledgeBase: (knowledgeBaseId: string, fileIds: string[]) => Promise<unknown>;
+ createImage: (payload: ReturnType<typeof buildAIEditRequest>) => Promise<CreateImageResult>;
+ createTopic: (title: string, visibility?: 'private' | 'public') => Promise<string>;
+ /**
+ * Key out the flat backdrop of a remove-background result. Resolves to the
+ * transparent PNG, or undefined when the backdrop was not flat enough to trust.
+ */
+ cutOutBackground: (url: string, name: string) => Promise<File | undefined>;
+ deleteTopic: (id: string) => Promise<unknown>;
+ /** Read a file's location and metadata; never used to write. */
+ getFile: (id: string) => Promise<
+ | {
+ knowledgeBaseIds?: string[];
+ metadata?: Record<string, unknown> | null;
+ parentId?: string | null;
+ size?: number | null;
+ visibility?: 'private' | 'public' | null;
+ }
+ | null
+ | undefined
+ >;
+ getStatus: (generationId: string, asyncTaskId: string) => Promise<GenerationStatusResult>;
+ removeFile: (id: string) => Promise<unknown>;
+ updateFile: (
+ id: string,
+ data: { metadata: Record<string, unknown>; name: string; parentId?: string },
+ ) => Promise<unknown>;
+ /** Upload a file into the library; used for the erase guide and as a fallback for the result. */
+ uploadFile: (params: {
+ file: File;
+ metadata?: Record<string, unknown>;
+ parentId?: string;
+ visibility?: 'private' | 'public';
+ }) => Promise<{ id: string; url: string } | undefined>;
+}
+
+export interface AIEditSource {
+ fileId: string;
+ name?: string;
+ parentId?: string | null;
+ url: string;
+}
+
+export interface RunAIImageEditParams {
+ deps: AIEditDeps;
+ /** Erase only: the image with the region to remove painted in the mark color. */
+ guide?: Blob;
+ model: AIEditModel;
+ onPhase?: (phase: AIEditPhase) => void;
+ operation: AIEditOperation;
+ pollInterval?: number;
+ /** How long to keep watching an abandoned task so its erase guide can be removed. */
+ settleWatch?: number;
+ signal?: AbortSignal;
+ source: AIEditSource;
+ timeout?: number;
+ /** Name of the generation topic the edit is recorded under. */
+ topicTitle: string;
+}
+
+export interface AIEditResult {
+ fileId: string;
+ height?: number;
+ /** Saved, but adding it to one of the original's libraries failed. */
+ libraryFailed?: boolean;
+ name: string;
+ url: string;
+ width?: number;
+}
+
+const DEFAULT_POLL_INTERVAL = 2000;
+const DEFAULT_TIMEOUT = 3 * 60 * 1000;
+const DEFAULT_SETTLE_WATCH = 30 * 60 * 1000;
+const SAVE_TIMEOUT = 60 * 1000;
+const MAX_SETTLE_WATCH_DELAY = 60 * 1000;
+
+const sleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) return reject(new AIImageEditError('cancelled'));
+ const timer = setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(timer);
+ reject(new AIImageEditError('cancelled'));
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
+
+/**
+ * Settle with `request`, unless cancel or the deadline comes first: a status
+ * request that hangs must not keep the tool locked.
+ */
+export const raceRequest = <T>(request: Promise<T>, deadline: number, signal?: AbortSignal) =>
+ new Promise<T>((resolve, reject) => {
+ if (signal?.aborted) return reject(new AIImageEditError('cancelled'));
+ const finish = () => {
+ clearTimeout(timer);
+ signal?.removeEventListener('abort', onAbort);
+ };
+ const onAbort = () => {
+ finish();
+ reject(new AIImageEditError('cancelled'));
+ };
+ // Whether a task may be running is decided by the caller, which knows
+ // whether anything was submitted yet.
+ const timer = setTimeout(
+ () => {
+ finish();
+ reject(new AIImageEditError('timeout'));
+ },
+ Math.max(0, deadline - Date.now()),
+ );
+ signal?.addEventListener('abort', onAbort, { once: true });
+ request.then(
+ (value) => {
+ finish();
+ resolve(value);
+ },
+ (error) => {
+ finish();
+ reject(error);
+ },
+ );
+ });
+
+const throwIfAborted = (signal?: AbortSignal) => {
+ if (signal?.aborted) throw new AIImageEditError('cancelled');
+};
+
+/**
+ * Remove the erase guide of a task the client stopped waiting for, once the
+ * task settles. Best effort: it lasts while the page stays open.
+ */
+const removeGuideWhenSettled = async (
+ deps: AIEditDeps,
+ task: { asyncTaskId: string; id: string },
+ guideFileId: string,
+ interval: number,
+ limit: number,
+) => {
+ const deadline = Date.now() + limit;
+ let delay = interval;
+ while (Date.now() < deadline) {
+ await sleep(delay);
+ const status = await deps.getStatus(task.id, task.asyncTaskId).catch(() => undefined);
+ if (status?.status === AsyncTaskStatus.Success || status?.status === AsyncTaskStatus.Error) {
+ await deps.removeFile(guideFileId).catch(() => undefined);
+ return;
+ }
+ // Back off while the status endpoint is failing, so an outage does not
+ // turn into a steady stream of requests.
+ delay = status ? interval : Math.min(delay * 2, MAX_SETTLE_WATCH_DELAY);
+ }
+};
+
+/** A request the server refused outright (4xx), so it started nothing. */
+const isRejectedRequest = (error: unknown) => {
+ const status = (error as { data?: { httpStatus?: number } } | undefined)?.data?.httpStatus;
+ return typeof status === 'number' && status >= 400 && status < 500;
+};
+
+const errorDetail = (error: AsyncTaskError | null | undefined) => {
+ const detail = error?.body?.detail;
+ if (typeof detail === 'string' && detail) return detail;
+ return error?.name;
+};
+
+/**
+ * Edit an image with the image generation pipeline and keep the output as a
+ * new library file next to the source. The source file is only ever read: the
+ * result is the generation's own file, renamed and filed beside the original.
+ *
+ * There is no way to abort a submitted generation task, so once it is running
+ * cancelling or timing out only stops the client from waiting. Once anything
+ * may have been submitted, the generation topic is kept: it holds the task's
+ * record and output, which appear under Image generation. Only a topic that
+ * never got a task is deleted. The erase guide is removed once the task has
+ * settled, by a background watch when the client stopped waiting earlier.
+ */
+export const runAIImageEdit = async ({
+ deps,
+ guide,
+ model,
+ onPhase,
+ operation,
+ pollInterval = DEFAULT_POLL_INTERVAL,
+ signal,
+ source,
+ settleWatch = DEFAULT_SETTLE_WATCH,
+ timeout = DEFAULT_TIMEOUT,
+ topicTitle,
+}: RunAIImageEditParams): Promise<AIEditResult> => {
+ let guideFileId: string | undefined;
+ let topicId: string | undefined;
+ let task: { asyncTaskId: string; id: string } | undefined;
+ let submitted = false;
+ let settled = false;
+
+ // One deadline for the whole run: every step before and after submitting
+ // races it and Cancel, so no hung request can keep the tool locked.
+ const deadline = Date.now() + timeout;
+ const step = <T>(request: Promise<T>) => raceRequest(request, deadline, signal);
+
+ try {
+ // The caller may have spent a while preparing the guide; honor a cancel from then.
+ throwIfAborted(signal);
+ let imageUrl = source.url;
+ // Read before the topic exists: the result inherits the topic's visibility,
+ // which should follow the original's, and the save step needs the location.
+ const location = await step(deps.getFile(source.fileId)).catch((error) => {
+ if (error instanceof AIImageEditError) throw error;
+ console.error('[ImageViewer] failed to read the original image location', error);
+ return undefined;
+ });
+
+ // The model's own limit on the reference image: refuse here instead of
+ // submitting a task the provider will reject.
+ const inputSize = operation === 'erase' ? guide?.size : (location?.size ?? undefined);
+ if (model.maxFileSize && inputSize && inputSize > model.maxFileSize)
+ throw new AIImageEditError(
+ 'tooLarge',
+ `Reference image is ${inputSize} bytes; the model accepts up to ${model.maxFileSize}`,
+ );
+
+ if (operation === 'erase') {
+ if (!guide) throw new AIImageEditError('failed', 'Missing erase guide image');
+ onPhase?.('uploading');
+ const guideUpload = deps.uploadFile({
+ file: new File([guide], buildDerivedFileName(source.name, 'erase-guide'), {
+ type: 'image/png',
+ }),
+ });
+ let uploaded: Awaited<typeof guideUpload>;
+ try {
+ uploaded = await step(guideUpload);
+ } catch (error) {
+ // Cancelled or timed out mid-upload: nothing was submitted, so remove
+ // the guide if the upload still lands.
+ void guideUpload.then((late) => late && deps.removeFile(late.id)).catch(() => undefined);
+ throw error;
+ }
+ if (!uploaded) throw new AIImageEditError('failed', 'Failed to upload the erase guide');
+ guideFileId = uploaded.id;
+ imageUrl = uploaded.url;
+ throwIfAborted(signal);
+ }
+
+ onPhase?.('generating');
+ const topicRequest = deps.createTopic(topicTitle, location?.visibility ?? undefined);
+ try {
+ topicId = await step(topicRequest);
+ } catch (error) {
+ // Cancelled or timed out while creating: nothing will ever use this
+ // topic, so drop it once it arrives.
+ void topicRequest.then((id) => deps.deleteTopic(id)).catch(() => undefined);
+ throw error;
+ }
+ throwIfAborted(signal);
+
+ let created: CreateImageResult;
+ try {
+ created = await step(
+ deps.createImage(
+ buildAIEditRequest({ generationTopicId: topicId, imageUrl, model, operation }),
+ ),
+ );
+ } catch (error) {
+ // The server starts the task before it answers, so a lost, failed or
+ // abandoned (cancel/deadline) response may hide a running job. Only an
+ // explicit rejection (4xx) proves nothing started.
+ if (!isRejectedRequest(error)) submitted = true;
+ throw error;
+ }
+ const pending = created?.data?.generations?.[0];
+ if (!created?.success || !pending?.id || !pending.asyncTaskId)
+ throw new AIImageEditError('failed', 'The image task could not be started');
+ submitted = true;
+ task = { asyncTaskId: pending.asyncTaskId, id: pending.id };
+
+ let generation: Generation | null = null;
+ while (!generation) {
+ await sleep(pollInterval, signal);
+ const status = await step(deps.getStatus(pending.id, pending.asyncTaskId));
+ if (status.status === AsyncTaskStatus.Success || status.status === AsyncTaskStatus.Error)
+ settled = true;
+ throwIfAborted(signal);
+
+ if (status.status === AsyncTaskStatus.Success) {
+ if (!status.generation?.asset?.url) throw new AIImageEditError('noResult');
+ generation = status.generation;
+ } else if (status.status === AsyncTaskStatus.Error) {
+ throw new AIImageEditError('failed', errorDetail(status.error));
+ } else if (Date.now() > deadline) {
+ throw new AIImageEditError('timeout', undefined, undefined, { taskRunning: true });
+ }
+ }
+
+ onPhase?.('saving');
+ // Saving gets its own window (generation may have used most of the run's),
+ // and still answers to Cancel.
+ const saveDeadline = Date.now() + SAVE_TIMEOUT;
+ const save = <T>(request: Promise<T>) => raceRequest(request, saveDeadline, signal);
+ const asset = generation.asset!;
+ const assetUrl = asset.url!;
+ const name = buildDerivedFileName(source.name, DERIVED_FILE_SUFFIX[operation]);
+ const lineage = buildDerivedFileMetadata(source.fileId, operation);
+ // The viewer may be opened from a view (e.g. the image list) that does not
+ // know where the original lives, so the server's folder and libraries win.
+ // The client's folder is only a fallback for when the lookup failed.
+ const parentId = (location ? location.parentId : source.parentId) ?? undefined;
+
+ // Older servers omit `fileId`, but a `/f/:id` asset URL still names the file.
+ let fileId = generation.fileId ?? fileIdFromProxyUrl(assetUrl);
+ let url = assetUrl;
+ // Image models cannot return an alpha channel, so the model paints a flat
+ // backdrop and it is keyed out here. The transparent PNG becomes the saved
+ // file; the generation's own output stays in its topic.
+ const cutOut =
+ operation === 'removeBackground'
+ ? await save(deps.cutOutBackground(assetUrl, name))
+ : undefined;
+ if (cutOut) {
+ const uploaded = await save(
+ deps.uploadFile({
+ file: cutOut,
+ metadata: lineage,
+ parentId,
+ visibility: location?.visibility ?? undefined,
+ }),
+ );
+ if (!uploaded) throw new AIImageEditError('failed', 'Failed to save the edited image');
+ fileId = uploaded.id;
+ url = uploaded.url;
+ } else if (fileId) {
+ // The generation already saved its output as a file; keep its storage
+ // metadata and add the lineage, then file it beside the original.
+ const metadata = (await save(deps.getFile(fileId)))?.metadata ?? {};
+ await save(
+ deps.updateFile(fileId, { metadata: { ...metadata, ...lineage }, name, parentId }),
+ );
+ } else {
+ // Older servers do not report the file; copy the asset into a new one.
+ const response = await save(fetch(assetUrl, { signal }));
+ if (!response.ok) throw new AIImageEditError('noResult', `HTTP ${response.status}`);
+ const blob = await save(response.blob());
+ const uploaded = await save(
+ deps.uploadFile({
+ file: new File([blob], name, { type: blob.type || 'image/png' }),
+ metadata: lineage,
+ parentId,
+ visibility: location?.visibility ?? undefined,
+ }),
+ );
+ if (!uploaded) throw new AIImageEditError('failed', 'Failed to save the edited image');
+ fileId = uploaded.id;
+ url = uploaded.url;
+ }
+
+ const libraryFailed = await fileIntoLibraries(
+ { addToKnowledgeBase: (id, fileIds) => save(deps.addToKnowledgeBase(id, fileIds)) },
+ location?.knowledgeBaseIds,
+ fileId,
+ );
+ throwIfAborted(signal);
+
+ return { fileId, height: asset.height, libraryFailed, name, url, width: asset.width };
+ } catch (error) {
+ // Once submitted, only a terminal status ends the task; a status request
+ // that fails leaves it running on the server.
+ const taskRunning = submitted && !settled;
+ if (signal?.aborted) throw new AIImageEditError('cancelled', undefined, error, { taskRunning });
+ if (error instanceof AIImageEditError) {
+ error.taskRunning ||= taskRunning;
+ throw error;
+ }
+ throw new AIImageEditError('failed', (error as Error)?.message, error, { taskRunning });
+ } finally {
+ // Cleanup is best effort and must never mask the outcome.
+ if (topicId && !submitted) await deps.deleteTopic(topicId).catch(() => undefined);
+ if (guideFileId) {
+ // A task still running needs its input image until it settles.
+ if (!submitted || settled) await deps.removeFile(guideFileId).catch(() => undefined);
+ else if (task)
+ void removeGuideWhenSettled(deps, task, guideFileId, pollInterval, settleWatch);
+ }
+ }
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/AIEdit/useAIImageEdit.ts b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/useAIImageEdit.ts
new file mode 100644
index 00000000000..23dc6c4b186
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/AIEdit/useAIImageEdit.ts
@@ -0,0 +1,151 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { aiProviderSelectors, getAiInfraStoreState } from '@/store/aiInfra';
+import { fileManagerSelectors, useFileStore } from '@/store/file';
+import { useGlobalStore } from '@/store/global';
+
+import { useImageStage } from '../../context';
+import { ImagePixelsUnavailableError } from '../exportImage';
+import { aiEditDeps } from './deps';
+import { type AIEditOperation, resolveAIEditModel } from './request';
+import {
+ type AIEditDeps,
+ type AIEditErrorKind,
+ type AIEditPhase,
+ type AIEditResult,
+ AIImageEditError,
+ raceRequest,
+ runAIImageEdit,
+} from './runAIImageEdit';
+
+const GUIDE_PREPARE_TIMEOUT = 60 * 1000;
+
+export type AIEditState =
+ | { status: 'idle' }
+ | { phase: AIEditPhase; startedAt: number; status: 'running' }
+ | {
+ kind: Exclude<AIEditErrorKind, 'cancelled'>;
+ message?: string;
+ status: 'error';
+ /** The server task keeps running; its result shows up in image generation. */
+ taskRunning?: boolean;
+ };
+
+/**
+ * Run one AI edit of the image on stage and track its progress. The result is
+ * saved as a new file next to the original; the original is never written.
+ */
+export const useAIImageEdit = (operation: AIEditOperation, deps: AIEditDeps = aiEditDeps) => {
+ const { t } = useTranslation('file');
+ const { addVersion, fileId, name, url } = useImageStage();
+ const [state, setState] = useState<AIEditState>({ status: 'idle' });
+ const controllerRef = useRef<AbortController | null>(null);
+
+ // Leaving the tool abandons the edit, same as pressing cancel.
+ useEffect(() => () => controllerRef.current?.abort(), []);
+
+ const run = useCallback(
+ async (prepareGuide?: () => Promise<Blob>): Promise<AIEditResult | undefined> => {
+ const { lastSelectedImageModel, lastSelectedImageProvider } =
+ useGlobalStore.getState().status;
+ const model = resolveAIEditModel(
+ aiProviderSelectors.enabledImageModelList(getAiInfraStoreState()),
+ { model: lastSelectedImageModel, provider: lastSelectedImageProvider },
+ );
+ if (!model) {
+ setState({ kind: 'noModel', status: 'error' });
+ return;
+ }
+
+ const controller = new AbortController();
+ controllerRef.current = controller;
+ const startedAt = Date.now();
+ setState({
+ phase: operation === 'erase' ? 'uploading' : 'generating',
+ startedAt,
+ status: 'running',
+ });
+
+ const source = fileManagerSelectors.getFileByChunkTargetId(fileId)(useFileStore.getState());
+
+ let guide: Blob | undefined;
+ if (prepareGuide) {
+ try {
+ // Reading and rendering the image can hang too; Cancel must still work.
+ guide = await raceRequest(
+ prepareGuide(),
+ Date.now() + GUIDE_PREPARE_TIMEOUT,
+ controller.signal,
+ );
+ } catch (error) {
+ if (controllerRef.current === controller) controllerRef.current = null;
+ setState({ status: 'idle' });
+ if (error instanceof AIImageEditError && error.kind === 'cancelled') {
+ toast.info(t('imageViewer.ai.cancelled'));
+ return;
+ }
+ console.error('[ImageViewer] erase guide render failed', error);
+ toast.error(
+ error instanceof ImagePixelsUnavailableError
+ ? t('imageViewer.pixelsUnavailable')
+ : t('imageViewer.saveFailed'),
+ );
+ return;
+ }
+ }
+
+ try {
+ const result = await runAIImageEdit({
+ deps,
+ guide,
+ model,
+ onPhase: (phase) => {
+ if (!controller.signal.aborted) setState({ phase, startedAt, status: 'running' });
+ },
+ operation,
+ signal: controller.signal,
+ source: { fileId, name, parentId: source?.parentId, url },
+ topicTitle: t('imageViewer.ai.topicTitle', {
+ name: name || 'image',
+ operation: t(`imageViewer.tool.${operation}`),
+ }),
+ });
+
+ setState({ status: 'idle' });
+ void useFileStore.getState().refreshFileList({ revalidateResources: true });
+ if (result.libraryFailed)
+ toast.warning(t('imageViewer.savedNotInLibrary', { name: result.name }));
+ else toast.success(t('imageViewer.saved', { name: result.name }));
+ addVersion({ fileId: result.fileId, name: result.name, operation, url: result.url });
+ return result;
+ } catch (error) {
+ const edit =
+ error instanceof AIImageEditError ? error : new AIImageEditError('failed', String(error));
+ if (edit.kind === 'cancelled') {
+ setState({ status: 'idle' });
+ toast.info(
+ t(edit.taskRunning ? 'imageViewer.ai.stoppedWaiting' : 'imageViewer.ai.cancelled'),
+ );
+ return;
+ }
+ console.error('[ImageViewer] AI edit failed', error);
+ setState({
+ kind: edit.kind,
+ message: edit.message,
+ status: 'error',
+ taskRunning: edit.taskRunning,
+ });
+ } finally {
+ if (controllerRef.current === controller) controllerRef.current = null;
+ }
+ },
+ [addVersion, deps, fileId, name, operation, t, url],
+ );
+
+ const cancel = useCallback(() => controllerRef.current?.abort(), []);
+ const reset = useCallback(() => setState({ status: 'idle' }), []);
+
+ return { cancel, reset, run, state };
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Annotate/index.tsx b/src/features/FileViewer/Renderer/Image/Tools/Annotate/index.tsx
new file mode 100644
index 00000000000..0347a75d948
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Annotate/index.tsx
@@ -0,0 +1,273 @@
+'use client';
+
+import { ActionIcon } from '@lobehub/ui/base-ui';
+import { BrushIcon, CheckIcon, SquareIcon, Trash2Icon, Undo2Icon } from 'lucide-react';
+import type { PointerEvent } from 'react';
+import { useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { useImageStage } from '../../context';
+import type { Point } from '../../geometry';
+import BarButton from '../BarButton';
+import type { ImageMarkup } from '../markup';
+import MarkupPreview from '../MarkupPreview';
+import SendToChatButton from '../SendToChatButton';
+import { toolStyles as styles } from '../styles';
+import { useToolKeys } from '../useToolKeys';
+import {
+ ANNOTATION_COLOR_NAMES,
+ ANNOTATION_COLORS,
+ ANNOTATION_SIZES,
+ type AnnotationShape,
+ type AnnotationTool,
+ drawBrushSegment,
+ drawShapes,
+ isMeaningfulShape,
+ rectFromPoints,
+} from './shapes';
+
+type SizeKey = keyof typeof ANNOTATION_SIZES;
+type AnnotationColor = (typeof ANNOTATION_COLORS)[number];
+
+/** Thinnest first, so the dots grow left to right. */
+const SIZE_KEYS: SizeKey[] = ['small', 'medium', 'large'];
+
+const nextOf = <T,>(list: readonly T[], current: T) =>
+ list[(list.indexOf(current) + 1) % list.length];
+
+/** A dot whose size shows the stroke width. */
+const SizeDot = ({ index }: { index: number }) => (
+ <span
+ style={{
+ background: 'currentColor',
+ borderRadius: '50%',
+ display: 'block',
+ height: 4 + index * 3,
+ width: 4 + index * 3,
+ }}
+ />
+);
+
+interface AnnotateModeProps {
+ markup: ImageMarkup;
+ onChange: (markup: ImageMarkup) => void;
+ onExit: () => void;
+ onSent: (sent: ImageMarkup) => void;
+}
+
+/**
+ * Brush and box annotations drawn over the image. They stay in the viewer's
+ * memory until the user adds the marked-up image to a chat message.
+ */
+const AnnotateMode = ({ markup, onChange, onExit, onSent }: AnnotateModeProps) => {
+ const { t } = useTranslation('file');
+ const { compact, overlayElement, toImagePoint } = useImageStage();
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const dragStart = useRef<Point | null>(null);
+
+ const [tool, setTool] = useState<AnnotationTool>('brush');
+ const [color, setColor] = useState<string>(ANNOTATION_COLORS[0]);
+ const [sizeKey, setSizeKey] = useState<SizeKey>('medium');
+ const { shapes } = markup;
+ const setShapes = (update: (value: AnnotationShape[]) => AnnotationShape[]) =>
+ onChange({ ...markup, shapes: update(shapes) });
+ const [redrawKey, setRedrawKey] = useState(0);
+ const [draft, setDraftState] = useState<AnnotationShape | null>(null);
+ const draftRef = useRef<AnnotationShape | null>(null);
+ const setDraft = (value: AnnotationShape | null) => {
+ draftRef.current = value;
+ setDraftState(value);
+ };
+
+ // Keep the canvas backing store matched to its displayed size so strokes stay crisp.
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !overlayElement) return;
+ const sync = () => {
+ const ratio = window.devicePixelRatio || 1;
+ canvas.width = Math.max(1, Math.round(overlayElement.clientWidth * ratio));
+ canvas.height = Math.max(1, Math.round(overlayElement.clientHeight * ratio));
+ setRedrawKey((value) => value + 1);
+ };
+ sync();
+ if (!('ResizeObserver' in window)) return;
+ const observer = new ResizeObserver(sync);
+ observer.observe(overlayElement);
+ return () => observer.disconnect();
+ }, [overlayElement]);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (!canvas || !ctx) return;
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ // The live brush stroke lives in the ref (it grows without re-rendering).
+ const live = draft ?? draftRef.current;
+ drawShapes(ctx, live ? [...shapes, live] : shapes, canvas.width, canvas.height);
+ }, [draft, shapes, redrawKey]);
+
+ const undo = () => setShapes((value) => value.slice(0, -1));
+
+ useToolKeys({ onEscape: onExit, onUndo: undo });
+
+ const handlePointerDown = (event: PointerEvent<HTMLCanvasElement>) => {
+ if (event.button !== 0) return;
+ event.stopPropagation();
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ dragStart.current = point;
+ const style = { color, size: ANNOTATION_SIZES[sizeKey] };
+ if (tool === 'brush') draftRef.current = { ...style, points: [point], type: 'brush' };
+ else setDraft({ ...style, rect: rectFromPoints(point, point), type: 'rect' });
+ };
+
+ const handlePointerMove = (event: PointerEvent<HTMLCanvasElement>) => {
+ const start = dragStart.current;
+ if (!start) return;
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ const value = draftRef.current;
+ if (!value) return;
+ if (value.type === 'rect') return setDraft({ ...value, rect: rectFromPoints(start, point) });
+
+ // Brush: grow the stroke in place and paint only the new segment.
+ const last = value.points.at(-1)!;
+ value.points.push(point);
+ const canvas = canvasRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (canvas && ctx) drawBrushSegment(ctx, value, last, point, canvas.width, canvas.height);
+ };
+
+ const handlePointerUp = () => {
+ dragStart.current = null;
+ const value = draftRef.current;
+ if (value && isMeaningfulShape(value)) setShapes((list) => [...list, value]);
+ setDraft(null);
+ };
+
+ return (
+ <>
+ <MarkupPreview comments={markup.comments} />
+ {overlayElement &&
+ createPortal(
+ <canvas
+ aria-label={t('imageViewer.annotate.hint')}
+ className={styles.overlayFill}
+ data-testid={'image-annotate-canvas'}
+ ref={canvasRef}
+ role={'img'}
+ style={{ cursor: 'crosshair', height: '100%', touchAction: 'none', width: '100%' }}
+ onPointerCancel={handlePointerUp}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ />,
+ overlayElement,
+ )}
+ <div className={styles.dock}>
+ <div aria-label={t('imageViewer.tool.annotate')} className={styles.bar} role={'toolbar'}>
+ <ActionIcon
+ active={tool === 'brush'}
+ aria-label={t('imageViewer.annotate.brush')}
+ aria-pressed={tool === 'brush'}
+ icon={BrushIcon}
+ size={'small'}
+ title={t('imageViewer.annotate.brush')}
+ onClick={() => setTool('brush')}
+ />
+ <ActionIcon
+ active={tool === 'rect'}
+ aria-label={t('imageViewer.annotate.rect')}
+ aria-pressed={tool === 'rect'}
+ icon={SquareIcon}
+ size={'small'}
+ title={t('imageViewer.annotate.rect')}
+ onClick={() => setTool('rect')}
+ />
+ <span className={styles.divider} />
+ {compact ? (
+ // One swatch that steps through the colors keeps a narrow bar on one line.
+ <button
+ aria-label={`${t('imageViewer.annotate.color')}: ${t(`imageViewer.annotate.colorName.${ANNOTATION_COLOR_NAMES[color as AnnotationColor]}`)}`}
+ className={styles.swatch}
+ style={{ background: color }}
+ title={t('imageViewer.annotate.color')}
+ type={'button'}
+ onClick={() => setColor(nextOf(ANNOTATION_COLORS, color as AnnotationColor))}
+ />
+ ) : (
+ <div
+ aria-label={t('imageViewer.annotate.color')}
+ role={'group'}
+ style={{ display: 'flex', gap: 6 }}
+ >
+ {ANNOTATION_COLORS.map((value) => (
+ <button
+ aria-label={t(`imageViewer.annotate.colorName.${ANNOTATION_COLOR_NAMES[value]}`)}
+ aria-pressed={color === value}
+ className={styles.swatch}
+ key={value}
+ style={{ background: value }}
+ type={'button'}
+ onClick={() => setColor(value)}
+ />
+ ))}
+ </div>
+ )}
+ <span className={styles.divider} />
+ {compact ? (
+ <ActionIcon
+ aria-label={t('imageViewer.annotate.size')}
+ icon={<SizeDot index={SIZE_KEYS.indexOf(sizeKey)} />}
+ size={'small'}
+ title={t('imageViewer.annotate.size')}
+ onClick={() => setSizeKey(nextOf(SIZE_KEYS, sizeKey))}
+ />
+ ) : (
+ <div
+ aria-label={t('imageViewer.annotate.size')}
+ role={'group'}
+ style={{ display: 'flex' }}
+ >
+ {SIZE_KEYS.map((key, index) => (
+ <ActionIcon
+ active={sizeKey === key}
+ aria-label={`${t('imageViewer.annotate.size')} ${index + 1}`}
+ aria-pressed={sizeKey === key}
+ icon={<SizeDot index={index} />}
+ key={key}
+ size={'small'}
+ onClick={() => setSizeKey(key)}
+ />
+ ))}
+ </div>
+ )}
+ <span className={styles.divider} />
+ <ActionIcon
+ aria-label={t('imageViewer.annotate.undo')}
+ disabled={shapes.length === 0}
+ icon={Undo2Icon}
+ size={'small'}
+ title={t('imageViewer.annotate.undo')}
+ onClick={undo}
+ />
+ <ActionIcon
+ aria-label={t('imageViewer.annotate.clear')}
+ disabled={shapes.length === 0}
+ icon={Trash2Icon}
+ size={'small'}
+ title={t('imageViewer.annotate.clear')}
+ onClick={() => setShapes(() => [])}
+ />
+ <span className={styles.divider} />
+ <BarButton icon={CheckIcon} label={t('imageViewer.done')} onClick={onExit} />
+ <SendToChatButton markup={markup} onSent={onSent} />
+ </div>
+ </div>
+ </>
+ );
+};
+
+export default AnnotateMode;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Annotate/shapes.test.ts b/src/features/FileViewer/Renderer/Image/Tools/Annotate/shapes.test.ts
new file mode 100644
index 00000000000..02adaa988a5
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Annotate/shapes.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ type AnnotationShape,
+ drawBrushSegment,
+ drawShapes,
+ isMeaningfulShape,
+ rectFromPoints,
+} from './shapes';
+
+const createCtx = () => ({
+ beginPath: vi.fn(),
+ lineCap: 'butt',
+ lineJoin: 'miter',
+ lineTo: vi.fn(),
+ lineWidth: 1,
+ moveTo: vi.fn(),
+ stroke: vi.fn(),
+ strokeRect: vi.fn(),
+ strokeStyle: '',
+});
+
+describe('annotation shapes', () => {
+ it('builds a rect from any drag direction', () => {
+ expect(rectFromPoints({ x: 0.8, y: 0.6 }, { x: 0.2, y: 0.1 })).toEqual({
+ height: 0.5,
+ width: expect.closeTo(0.6),
+ x: 0.2,
+ y: 0.1,
+ });
+ });
+
+ it('drops clicks that would export as nothing', () => {
+ expect(
+ isMeaningfulShape({ color: '#f00', points: [{ x: 0, y: 0 }], size: 0.01, type: 'brush' }),
+ ).toBe(false);
+ expect(
+ isMeaningfulShape({
+ color: '#f00',
+ rect: { height: 0, width: 0.3, x: 0, y: 0 },
+ size: 0.01,
+ type: 'rect',
+ }),
+ ).toBe(false);
+ });
+
+ it('draws normalized shapes in canvas pixels', () => {
+ const ctx = createCtx();
+ const shapes: AnnotationShape[] = [
+ {
+ color: '#ff0000',
+ rect: { height: 0.5, width: 0.25, x: 0.1, y: 0.2 },
+ size: 0.01,
+ type: 'rect',
+ },
+ {
+ color: '#00ff00',
+ points: [
+ { x: 0, y: 0 },
+ { x: 0.5, y: 0.5 },
+ ],
+ size: 0.02,
+ type: 'brush',
+ },
+ ];
+
+ drawShapes(ctx as never, shapes, 400, 200);
+
+ expect(ctx.strokeRect).toHaveBeenCalledWith(40, 40, 100, 100);
+ expect(ctx.moveTo).toHaveBeenCalledWith(0, 0);
+ expect(ctx.lineTo).toHaveBeenCalledWith(200, 100);
+ // Stroke width scales with the shorter side: 0.02 × 200.
+ expect(ctx.lineWidth).toBe(4);
+ expect(ctx.strokeStyle).toBe('#00ff00');
+ });
+});
+
+describe('drawBrushSegment', () => {
+ it('strokes only the newest segment in canvas pixels', () => {
+ const ctx = {
+ beginPath: vi.fn(),
+ lineCap: '',
+ lineJoin: '',
+ lineTo: vi.fn(),
+ lineWidth: 0,
+ moveTo: vi.fn(),
+ stroke: vi.fn(),
+ strokeStyle: '',
+ };
+ drawBrushSegment(
+ ctx as never,
+ { color: '#f00', size: 0.01 },
+ { x: 0.1, y: 0.2 },
+ { x: 0.3, y: 0.4 },
+ 200,
+ 100,
+ );
+
+ expect(ctx.moveTo).toHaveBeenCalledWith(20, 20);
+ expect(ctx.lineTo).toHaveBeenCalledTimes(1);
+ expect(ctx.lineTo).toHaveBeenCalledWith(60, 40);
+ expect(ctx.stroke).toHaveBeenCalledTimes(1);
+ expect(ctx.lineWidth).toBe(1);
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Annotate/shapes.ts b/src/features/FileViewer/Renderer/Image/Tools/Annotate/shapes.ts
new file mode 100644
index 00000000000..aa682e04911
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Annotate/shapes.ts
@@ -0,0 +1,120 @@
+import type { NormalizedRect, Point } from '../../geometry';
+
+export type AnnotationTool = 'brush' | 'rect';
+
+interface ShapeStyle {
+ color: string;
+ /** Stroke width as a fraction of the image's shorter side, so it scales with export size. */
+ size: number;
+}
+
+export interface BrushShape extends ShapeStyle {
+ points: Point[];
+ type: 'brush';
+}
+
+export interface RectShape extends ShapeStyle {
+ rect: NormalizedRect;
+ type: 'rect';
+}
+
+export type AnnotationShape = BrushShape | RectShape;
+
+export const ANNOTATION_COLORS = ['#ff3b30', '#ffcc00', '#34c759', '#0a84ff', '#ffffff'] as const;
+
+/** Spoken names for the swatches, keyed by color (locale key suffix). */
+export const ANNOTATION_COLOR_NAMES: Record<
+ (typeof ANNOTATION_COLORS)[number],
+ 'blue' | 'green' | 'red' | 'white' | 'yellow'
+> = {
+ '#0a84ff': 'blue',
+ '#34c759': 'green',
+ '#ff3b30': 'red',
+ '#ffcc00': 'yellow',
+ '#ffffff': 'white',
+};
+
+export const ANNOTATION_SIZES = {
+ large: 0.012,
+ medium: 0.006,
+ small: 0.003,
+} as const;
+
+/** Rectangle spanned by two drag points, whichever corner the drag started from. */
+export const rectFromPoints = (a: Point, b: Point): NormalizedRect => ({
+ height: Math.abs(b.y - a.y),
+ width: Math.abs(b.x - a.x),
+ x: Math.min(a.x, b.x),
+ y: Math.min(a.y, b.y),
+});
+
+/** Drop accidental clicks that would export as a dot or a zero-size box. */
+export const isMeaningfulShape = (shape: AnnotationShape) =>
+ shape.type === 'brush'
+ ? shape.points.length > 1
+ : shape.rect.width > 0.002 && shape.rect.height > 0.002;
+
+type DrawingContext = Pick<
+ CanvasRenderingContext2D,
+ | 'beginPath'
+ | 'lineTo'
+ | 'moveTo'
+ | 'stroke'
+ | 'strokeRect'
+ | 'lineCap'
+ | 'lineJoin'
+ | 'lineWidth'
+ | 'strokeStyle'
+>;
+
+/**
+ * Extend a brush stroke by its newest segment only, so a long freehand stroke
+ * costs one segment per pointer move instead of a full redraw.
+ */
+export const drawBrushSegment = (
+ ctx: DrawingContext,
+ shape: Pick<BrushShape, 'color' | 'size'>,
+ from: Point,
+ to: Point,
+ width: number,
+ height: number,
+) => {
+ ctx.strokeStyle = shape.color;
+ ctx.lineWidth = Math.max(1, shape.size * Math.min(width, height));
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ ctx.beginPath();
+ ctx.moveTo(from.x * width, from.y * height);
+ ctx.lineTo(to.x * width, to.y * height);
+ ctx.stroke();
+};
+
+/** Paint shapes in pixel space of a `width × height` canvas. */
+export const drawShapes = (
+ ctx: DrawingContext,
+ shapes: AnnotationShape[],
+ width: number,
+ height: number,
+) => {
+ const unit = Math.min(width, height);
+
+ for (const shape of shapes) {
+ ctx.strokeStyle = shape.color;
+ ctx.lineWidth = Math.max(1, shape.size * unit);
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+
+ if (shape.type === 'rect') {
+ const { x, y, width: w, height: h } = shape.rect;
+ ctx.strokeRect(x * width, y * height, w * width, h * height);
+ continue;
+ }
+
+ const [first, ...rest] = shape.points;
+ if (!first) continue;
+ ctx.beginPath();
+ ctx.moveTo(first.x * width, first.y * height);
+ for (const point of rest) ctx.lineTo(point.x * width, point.y * height);
+ ctx.stroke();
+ }
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/BarButton.tsx b/src/features/FileViewer/Renderer/Image/Tools/BarButton.tsx
new file mode 100644
index 00000000000..3fc89a8b948
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/BarButton.tsx
@@ -0,0 +1,40 @@
+'use client';
+
+import { Button, type ButtonProps } from '@lobehub/ui/base-ui';
+import type { LucideIcon } from 'lucide-react';
+import type { ReactNode } from 'react';
+
+import { useImageStage } from '../context';
+
+interface BarButtonProps extends Omit<ButtonProps, 'children' | 'icon' | 'shape' | 'size'> {
+ /** Shown after the label (e.g. a count); dropped when the bar is compact. */
+ extra?: ReactNode;
+ icon: LucideIcon;
+ label: string;
+}
+
+/**
+ * A tool bar button: icon and label, or the icon alone (label as tooltip) when
+ * the viewer is narrow, so a bar always stays on one line.
+ */
+const BarButton = ({ extra, icon, label, title, ...rest }: BarButtonProps) => {
+ const { compact } = useImageStage();
+
+ return compact ? (
+ <Button
+ {...rest}
+ aria-label={label}
+ icon={icon}
+ shape={'circle'}
+ size={'small'}
+ title={title ?? label}
+ />
+ ) : (
+ <Button {...rest} icon={icon} shape={'round'} size={'small'} title={title}>
+ {label}
+ {extra}
+ </Button>
+ );
+};
+
+export default BarButton;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Comment/CommentMarkers.tsx b/src/features/FileViewer/Renderer/Image/Tools/Comment/CommentMarkers.tsx
new file mode 100644
index 00000000000..b54ccc4255f
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Comment/CommentMarkers.tsx
@@ -0,0 +1,122 @@
+'use client';
+
+import { createStaticStyles, cssVar } from 'antd-style';
+import { useTranslation } from 'react-i18next';
+
+import type { Rotation } from '../../geometry';
+import { anchorOrigin, MARKER_COLOR, type MarkupComment } from '../markup';
+
+export const markerStyles = createStaticStyles(({ css }) => ({
+ pin: css`
+ cursor: pointer;
+
+ position: absolute;
+ z-index: 1;
+
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ width: 24px;
+ height: 24px;
+ margin-block-start: -12px;
+ margin-inline-start: -12px;
+ padding: 0;
+ border: 2px solid #fff;
+ border-radius: 50%;
+
+ font-size: 11px;
+ font-weight: 600;
+ color: #fff;
+
+ background: ${MARKER_COLOR};
+ box-shadow: ${cssVar.boxShadowSecondary};
+
+ &[data-active='true'] {
+ background: ${cssVar.colorWarning};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 2px;
+ }
+ `,
+ region: css`
+ pointer-events: none;
+
+ position: absolute;
+
+ border: 2px dashed ${MARKER_COLOR};
+ border-radius: 2px;
+
+ background: color-mix(in srgb, ${MARKER_COLOR} 8%, transparent);
+
+ &[data-active='true'] {
+ border-color: ${cssVar.colorWarning};
+ }
+ `,
+}));
+
+interface CommentMarkersProps {
+ activeId?: string;
+ comments: MarkupComment[];
+ /** Read-only markers ignore the pointer, so the layer under them keeps working. */
+ onSelect?: (id: string) => void;
+ rotation: Rotation;
+}
+
+/**
+ * Numbered markers for the comments on the image: a pin at a point, or a
+ * dashed box with its pin at the top-left corner. The numbers match the ones
+ * drawn into the exported image and the lines of the chat message.
+ */
+const CommentMarkers = ({ activeId, comments, onSelect, rotation }: CommentMarkersProps) => {
+ const { t } = useTranslation('file');
+ // Markers sit inside the rotated frame; turning them back keeps labels upright.
+ const upright = { transform: `rotate(${-rotation}deg)` };
+
+ return comments.map((comment, index) => {
+ const origin = anchorOrigin(comment.anchor);
+ const active = activeId === comment.id;
+ return (
+ <span key={comment.id}>
+ {comment.anchor.type === 'region' && (
+ <span
+ className={markerStyles.region}
+ data-active={active}
+ data-testid={'image-comment-region'}
+ style={{
+ height: `${comment.anchor.rect.height * 100}%`,
+ left: `${comment.anchor.rect.x * 100}%`,
+ top: `${comment.anchor.rect.y * 100}%`,
+ width: `${comment.anchor.rect.width * 100}%`,
+ }}
+ />
+ )}
+ <button
+ aria-label={t('imageViewer.comment.pin', { index: index + 1 })}
+ className={markerStyles.pin}
+ data-active={active}
+ tabIndex={onSelect ? undefined : -1}
+ title={comment.text}
+ type={'button'}
+ style={{
+ left: `${origin.x * 100}%`,
+ pointerEvents: onSelect ? undefined : 'none',
+ top: `${origin.y * 100}%`,
+ ...upright,
+ }}
+ onPointerDown={(event) => event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onSelect?.(comment.id);
+ }}
+ >
+ {index + 1}
+ </button>
+ </span>
+ );
+ });
+};
+
+export default CommentMarkers;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Comment/index.tsx b/src/features/FileViewer/Renderer/Image/Tools/Comment/index.tsx
new file mode 100644
index 00000000000..932e8630b8a
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Comment/index.tsx
@@ -0,0 +1,393 @@
+'use client';
+
+import { nanoid } from '@lobechat/utils';
+import { ActionIcon, Button, Text, TextArea } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CheckIcon, ListIcon, Trash2Icon } from 'lucide-react';
+import type { PointerEvent } from 'react';
+import { useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { useImageStage } from '../../context';
+import { imagePointToScreenFraction, type Point } from '../../geometry';
+import { rectFromPoints } from '../Annotate/shapes';
+import BarButton from '../BarButton';
+import {
+ anchorOrigin,
+ describeAnchor,
+ type ImageMarkup,
+ MARKUP_COMMENT_MAX_LENGTH,
+ type MarkupAnchor,
+} from '../markup';
+import MarkupPreview from '../MarkupPreview';
+import SendToChatButton from '../SendToChatButton';
+import { toolStyles } from '../styles';
+import { useToolKeys } from '../useToolKeys';
+import CommentMarkers, { markerStyles } from './CommentMarkers';
+
+/** A drag shorter than this (in image fractions) is a click on a point. */
+const REGION_MIN_SIZE = 0.02;
+
+const styles = createStaticStyles(({ css }) => ({
+ draft: css`
+ position: absolute;
+ z-index: 2;
+
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+
+ width: 240px;
+ padding: 8px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowSecondary};
+ `,
+ item: css`
+ cursor: pointer;
+
+ display: flex;
+ gap: 8px;
+ align-items: flex-start;
+
+ padding: 8px;
+ border-radius: ${cssVar.borderRadius};
+
+ &:hover,
+ &[data-active='true'] {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ pinBadge: css`
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ justify-content: center;
+
+ width: 20px;
+ height: 20px;
+ border-radius: 10px;
+
+ font-size: 11px;
+ font-weight: 600;
+ color: #fff;
+
+ background: ${cssVar.colorInfo};
+ `,
+}));
+
+interface CommentModeProps {
+ markup: ImageMarkup;
+ onChange: (markup: ImageMarkup) => void;
+ onExit: () => void;
+ onSent: (sent: ImageMarkup) => void;
+}
+
+/**
+ * Pin comments on a point of the image, or drag to comment on a region. They
+ * stay in the viewer's memory until the user adds them to a chat message.
+ * Anchors are normalized, so they stay on the same pixels through zoom and
+ * rotation.
+ */
+const CommentMode = ({ markup, onChange, onExit, onSent }: CommentModeProps) => {
+ const { t } = useTranslation('file');
+ const { compact, overlayElement, rotation, setReserve, toImagePoint } = useImageStage();
+ const { comments } = markup;
+
+ const dragStart = useRef<Point | null>(null);
+ const [dragAnchor, setDragAnchor] = useState<MarkupAnchor | null>(null);
+ const [draftAnchor, setDraftAnchor] = useState<MarkupAnchor | null>(null);
+ const [draftText, setDraftText] = useState('');
+ const [activeId, setActiveId] = useState<string>();
+ // In a narrow host (the chat preview, the resource detail dock) the list
+ // starts collapsed and opens from the bottom bar.
+ const [listOpen, setListOpen] = useState(!compact);
+ const panelRef = useRef<HTMLElement>(null);
+
+ // The list never covers the image: it takes a column on the right (wide) or
+ // a sheet above the bar (narrow), and the viewer shrinks the stage by it.
+ useEffect(() => {
+ const panel = panelRef.current;
+ if (!listOpen || !panel) {
+ setReserve({});
+ return;
+ }
+ const sync = () =>
+ setReserve(compact ? { bottom: panel.offsetHeight + 8 } : { right: panel.offsetWidth + 16 });
+ sync();
+ if (!('ResizeObserver' in window)) return;
+ const observer = new ResizeObserver(sync);
+ observer.observe(panel);
+ return () => observer.disconnect();
+ }, [compact, listOpen, setReserve]);
+ useEffect(() => () => setReserve({}), [setReserve]);
+
+ const cancelDraft = () => {
+ setDraftAnchor(null);
+ setDraftText('');
+ };
+
+ useToolKeys({ onEscape: () => (draftAnchor ? cancelDraft() : onExit()) });
+
+ /** Add the comment being typed, if any, and return the marks including it. */
+ const commitDraft = (): ImageMarkup => {
+ const text = draftText.trim();
+ if (!draftAnchor || !text) return markup;
+ const comment = { anchor: draftAnchor, id: nanoid(), text };
+ const next = { ...markup, comments: [...comments, comment] };
+ onChange(next);
+ setActiveId(comment.id);
+ cancelDraft();
+ return next;
+ };
+
+ const submitDraft = () => void commitDraft();
+
+ // A typed but not yet added comment counts: Done and Add to chat keep it.
+ const pendingText = draftAnchor ? draftText.trim() : '';
+ const sendableMarkup = pendingText
+ ? {
+ ...markup,
+ comments: [...comments, { anchor: draftAnchor!, id: 'pending', text: pendingText }],
+ }
+ : markup;
+
+ const removeComment = (id: string) =>
+ onChange({ ...markup, comments: comments.filter((comment) => comment.id !== id) });
+
+ const toAnchor = (start: Point, end: Point): MarkupAnchor => {
+ const rect = rectFromPoints(start, end);
+ return rect.width < REGION_MIN_SIZE && rect.height < REGION_MIN_SIZE
+ ? { point: start, type: 'point' }
+ : { rect, type: 'region' };
+ };
+
+ const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ event.stopPropagation();
+ if (event.button !== 0 || event.target !== event.currentTarget) return;
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ event.currentTarget.setPointerCapture?.(event.pointerId);
+ dragStart.current = point;
+ setActiveId(undefined);
+ };
+
+ const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ const start = dragStart.current;
+ if (!start) return;
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (point) setDragAnchor(toAnchor(start, point));
+ };
+
+ const handlePointerUp = (event: PointerEvent<HTMLDivElement>) => {
+ const start = dragStart.current;
+ dragStart.current = null;
+ setDragAnchor(null);
+ if (!start) return;
+ const point = toImagePoint({ x: event.clientX, y: event.clientY }) ?? start;
+ setDraftAnchor(toAnchor(start, point));
+ };
+
+ const pendingAnchor = dragAnchor ?? draftAnchor;
+ const draftOrigin = draftAnchor ? anchorOrigin(draftAnchor) : undefined;
+ // Which way the draft card opens depends on where the point is on screen,
+ // not in the image, once the image is turned.
+ const draftScreen = draftOrigin ? imagePointToScreenFraction(draftOrigin, rotation) : undefined;
+
+ return (
+ <>
+ <MarkupPreview shapes={markup.shapes} />
+ {overlayElement &&
+ createPortal(
+ <div
+ aria-label={t('imageViewer.comment.hint')}
+ className={toolStyles.overlayFill}
+ data-testid={'image-comment-layer'}
+ style={{ cursor: 'crosshair', touchAction: 'none' }}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerCancel={() => {
+ dragStart.current = null;
+ setDragAnchor(null);
+ }}
+ >
+ <CommentMarkers
+ activeId={activeId}
+ comments={comments}
+ rotation={rotation}
+ onSelect={setActiveId}
+ />
+ {pendingAnchor?.type === 'region' && (
+ <span
+ data-active
+ className={markerStyles.region}
+ style={{
+ height: `${pendingAnchor.rect.height * 100}%`,
+ left: `${pendingAnchor.rect.x * 100}%`,
+ top: `${pendingAnchor.rect.y * 100}%`,
+ width: `${pendingAnchor.rect.width * 100}%`,
+ }}
+ />
+ )}
+ {draftAnchor && draftOrigin && (
+ <>
+ <span
+ aria-hidden
+ data-active
+ className={markerStyles.pin}
+ style={{
+ left: `${draftOrigin.x * 100}%`,
+ top: `${draftOrigin.y * 100}%`,
+ transform: `rotate(${-rotation}deg)`,
+ }}
+ >
+ {comments.length + 1}
+ </span>
+ <div
+ className={styles.draft}
+ data-testid={'image-comment-draft'}
+ style={{
+ left: `${draftOrigin.x * 100}%`,
+ top: `${draftOrigin.y * 100}%`,
+ transform: `rotate(${-rotation}deg) translate(${draftScreen && draftScreen.x > 0.6 ? 'calc(-100% - 16px)' : '16px'}, ${draftScreen && draftScreen.y > 0.6 ? '-100%' : '0'})`,
+ transformOrigin: '0 0',
+ }}
+ onPointerDown={(event) => event.stopPropagation()}
+ >
+ <TextArea
+ autoFocus
+ aria-label={t('imageViewer.comment.add')}
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ maxLength={MARKUP_COMMENT_MAX_LENGTH}
+ placeholder={t('imageViewer.comment.placeholder')}
+ value={draftText}
+ onChange={(event) => setDraftText(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Escape') {
+ event.stopPropagation();
+ cancelDraft();
+ } else if (
+ event.key === 'Enter' &&
+ !event.shiftKey &&
+ !event.nativeEvent.isComposing
+ ) {
+ event.preventDefault();
+ submitDraft();
+ }
+ }}
+ />
+ <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
+ <Button size={'small'} onClick={cancelDraft}>
+ {t('imageViewer.cancel')}
+ </Button>
+ <Button
+ disabled={!draftText.trim()}
+ size={'small'}
+ type={'primary'}
+ onClick={submitDraft}
+ >
+ {t('imageViewer.comment.post')}
+ </Button>
+ </div>
+ </div>
+ </>
+ )}
+ </div>,
+ overlayElement,
+ )}
+
+ {listOpen && (
+ <aside
+ aria-label={t('imageViewer.comment.title')}
+ className={compact ? toolStyles.sheet : toolStyles.panel}
+ data-placement={compact ? 'bottom' : 'side'}
+ data-testid={'image-comment-panel'}
+ ref={panelRef}
+ >
+ <div
+ style={{
+ alignItems: 'center',
+ borderBottom: `1px solid ${cssVar.colorSplit}`,
+ display: 'flex',
+ fontWeight: 500,
+ gap: 6,
+ padding: '10px 12px',
+ }}
+ >
+ <span>{t('imageViewer.comment.title')}</span>
+ {comments.length > 0 && <Text type={'secondary'}>{comments.length}</Text>}
+ </div>
+ <div style={{ flex: 1, overflow: 'auto', padding: 4 }}>
+ {comments.length === 0 ? (
+ <Text style={{ display: 'block', padding: 12 }} type={'secondary'}>
+ {t('imageViewer.comment.empty')}
+ </Text>
+ ) : (
+ <ol style={{ listStyle: 'none', margin: 0, padding: 0 }}>
+ {comments.map((comment, index) => (
+ <li
+ className={styles.item}
+ data-active={activeId === comment.id}
+ key={comment.id}
+ onClick={() => setActiveId(comment.id)}
+ >
+ <span className={styles.pinBadge}>{index + 1}</span>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>
+ {comment.text}
+ </div>
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {describeAnchor(comment.anchor, t)}
+ </Text>
+ </div>
+ <ActionIcon
+ aria-label={t('imageViewer.comment.delete')}
+ icon={Trash2Icon}
+ size={'small'}
+ title={t('imageViewer.comment.delete')}
+ onClick={(event) => {
+ event.stopPropagation();
+ removeComment(comment.id);
+ }}
+ />
+ </li>
+ ))}
+ </ol>
+ )}
+ </div>
+ </aside>
+ )}
+
+ <div className={toolStyles.dock}>
+ <div aria-label={t('imageViewer.tool.comment')} className={toolStyles.bar} role={'toolbar'}>
+ {!compact && <span className={toolStyles.hint}>{t('imageViewer.comment.hint')}</span>}
+ <ActionIcon
+ active={listOpen}
+ aria-expanded={listOpen}
+ aria-label={t('imageViewer.comment.title')}
+ icon={ListIcon}
+ size={'small'}
+ title={t('imageViewer.comment.title')}
+ onClick={() => setListOpen((value) => !value)}
+ />
+ <span className={toolStyles.divider} />
+ <BarButton
+ icon={CheckIcon}
+ label={t('imageViewer.done')}
+ onClick={() => {
+ commitDraft();
+ onExit();
+ }}
+ />
+ <SendToChatButton markup={sendableMarkup} onBeforeSend={commitDraft} onSent={onSent} />
+ </div>
+ </div>
+ </>
+ );
+};
+
+export default CommentMode;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/MarkupPreview.tsx b/src/features/FileViewer/Renderer/Image/Tools/MarkupPreview.tsx
new file mode 100644
index 00000000000..fe0b18d1b44
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/MarkupPreview.tsx
@@ -0,0 +1,72 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+
+import { useImageStage } from '../context';
+import { type AnnotationShape, drawShapes } from './Annotate/shapes';
+import CommentMarkers from './Comment/CommentMarkers';
+import type { MarkupComment } from './markup';
+import { toolStyles } from './styles';
+
+interface MarkupPreviewProps {
+ comments?: MarkupComment[];
+ shapes?: AnnotationShape[];
+}
+
+/**
+ * Read-only view of the pending marks over the image, so drawings stay visible
+ * while commenting (and comments while drawing). It ignores the pointer.
+ */
+const MarkupPreview = ({ comments = [], shapes = [] }: MarkupPreviewProps) => {
+ const { overlayElement, rotation } = useImageStage();
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const [size, setSize] = useState({ height: 0, width: 0 });
+
+ useEffect(() => {
+ if (!overlayElement || shapes.length === 0) return;
+ const sync = () => {
+ const ratio = window.devicePixelRatio || 1;
+ setSize({
+ height: Math.max(1, Math.round(overlayElement.clientHeight * ratio)),
+ width: Math.max(1, Math.round(overlayElement.clientWidth * ratio)),
+ });
+ };
+ sync();
+ if (!('ResizeObserver' in window)) return;
+ const observer = new ResizeObserver(sync);
+ observer.observe(overlayElement);
+ return () => observer.disconnect();
+ }, [overlayElement, shapes.length]);
+
+ useEffect(() => {
+ const ctx = canvasRef.current?.getContext('2d');
+ if (!ctx) return;
+ ctx.clearRect(0, 0, size.width, size.height);
+ drawShapes(ctx, shapes, size.width, size.height);
+ }, [shapes, size]);
+
+ if (!overlayElement || (comments.length === 0 && shapes.length === 0)) return null;
+
+ return createPortal(
+ <div
+ className={toolStyles.overlayFill}
+ data-testid={'image-markup-preview'}
+ style={{ pointerEvents: 'none' }}
+ >
+ {shapes.length > 0 && (
+ <canvas
+ aria-hidden
+ height={size.height}
+ ref={canvasRef}
+ style={{ height: '100%', inset: 0, position: 'absolute', width: '100%' }}
+ width={size.width}
+ />
+ )}
+ <CommentMarkers comments={comments} rotation={rotation} />
+ </div>,
+ overlayElement,
+ );
+};
+
+export default MarkupPreview;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Resize/crop.test.ts b/src/features/FileViewer/Renderer/Image/Tools/Resize/crop.test.ts
new file mode 100644
index 00000000000..0682e43f887
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Resize/crop.test.ts
@@ -0,0 +1,131 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ aspectRatioOf,
+ centeredCrop,
+ cropPixelSize,
+ dragCrop,
+ MAX_OUTPUT_EDGE,
+ resolveOutputSize,
+} from './crop';
+
+const natural = { height: 1000, width: 2000 };
+
+describe('aspect presets', () => {
+ it('resolves preset ratios', () => {
+ expect(aspectRatioOf('free', natural)).toBeUndefined();
+ expect(aspectRatioOf('original', natural)).toBe(2);
+ expect(aspectRatioOf('16:9', natural)).toBeCloseTo(16 / 9);
+ });
+
+ it('centers the largest crop for a ratio', () => {
+ // A square out of a 2:1 image is the middle half horizontally.
+ expect(centeredCrop(natural, 1)).toEqual({ height: 1, width: 0.5, x: 0.25, y: 0 });
+ // A 4:1 strip out of a 2:1 image is the middle half vertically.
+ expect(centeredCrop(natural, 4)).toEqual({ height: 0.5, width: 1, x: 0, y: 0.25 });
+ expect(centeredCrop(natural, undefined)).toEqual({ height: 1, width: 1, x: 0, y: 0 });
+ });
+});
+
+describe('dragCrop', () => {
+ const start = { height: 0.5, width: 0.5, x: 0.25, y: 0.25 };
+
+ it('moves the crop and keeps it inside the image', () => {
+ expect(dragCrop(start, 'move', { x: 0.1, y: -0.1 }, natural)).toEqual({
+ height: 0.5,
+ width: 0.5,
+ x: 0.35,
+ y: 0.15,
+ });
+ expect(dragCrop(start, 'move', { x: 1, y: 1 }, natural)).toMatchObject({ x: 0.5, y: 0.5 });
+ });
+
+ it('resizes from a corner against the opposite corner', () => {
+ const next = dragCrop(start, 'nw', { x: -0.1, y: -0.1 }, natural);
+ expect(next.x).toBeCloseTo(0.15);
+ expect(next.y).toBeCloseTo(0.15);
+ expect(next.width).toBeCloseTo(0.6);
+ expect(next.height).toBeCloseTo(0.6);
+ });
+
+ it('keeps a locked pixel aspect while resizing', () => {
+ const next = dragCrop(start, 'se', { x: 0.1, y: 0 }, natural, 1);
+ const px = cropPixelSize(next, natural);
+ expect(px.width).toBe(px.height);
+ });
+
+ it('never grows past the image edge', () => {
+ const next = dragCrop(start, 'se', { x: 5, y: 5 }, natural);
+ expect(next.x + next.width).toBeLessThanOrEqual(1);
+ expect(next.y + next.height).toBeLessThanOrEqual(1);
+ });
+});
+
+describe('resolveOutputSize', () => {
+ const crop = { height: 500, width: 1000 };
+
+ it('derives the other side from the edited one when locked', () => {
+ expect(resolveOutputSize(crop, { edited: 'width', height: 0, width: 400 }, true)).toEqual({
+ height: 200,
+ width: 400,
+ });
+ expect(resolveOutputSize(crop, { edited: 'height', height: 300, width: 0 }, true)).toEqual({
+ height: 300,
+ width: 600,
+ });
+ });
+
+ it('accepts both sides when unlocked and clamps to safe bounds', () => {
+ expect(resolveOutputSize(crop, { edited: 'width', height: 10, width: 99_999 }, false)).toEqual({
+ height: 10,
+ width: MAX_OUTPUT_EDGE,
+ });
+ });
+});
+
+describe('cropPixelSize', () => {
+ it('is the crop at natural resolution', () => {
+ expect(
+ cropPixelSize({ height: 0.5, width: 0.5, x: 0, y: 0 }, { height: 1000, width: 2000 }),
+ ).toEqual({ height: 500, width: 1000 });
+ });
+
+ // Regression: a huge source started the output above the cap, so Save
+ // allocated a canvas the browser could refuse.
+ it('scales a crop larger than the output cap down to it, keeping the ratio', () => {
+ expect(
+ cropPixelSize({ height: 1, width: 1, x: 0, y: 0 }, { height: 10_000, width: 20_000 }),
+ ).toEqual({ height: MAX_OUTPUT_EDGE / 2, width: MAX_OUTPUT_EDGE });
+ });
+});
+
+describe('dragCrop with a locked aspect', () => {
+ const natural = { height: 1000, width: 1000 };
+ const start = { height: 0.5, width: 0.5, x: 0, y: 0 };
+
+ // Regression: a vertical drag on a corner did nothing once the ratio was locked.
+ it('follows a vertical corner drag', () => {
+ const next = dragCrop(start, 'se', { x: 0, y: 0.2 }, natural, 1);
+ expect(next.height).toBeCloseTo(0.7);
+ expect(next.width).toBeCloseTo(0.7);
+ });
+
+ it('follows a horizontal corner drag', () => {
+ const next = dragCrop(start, 'se', { x: -0.2, y: 0 }, natural, 1);
+ expect(next.width).toBeCloseTo(0.3);
+ expect(next.height).toBeCloseTo(0.3);
+ });
+});
+
+describe('resolveOutputSize at the cap', () => {
+ // Regression: a locked 2:1 crop at height 8192 clamped to 8192x8192.
+ it('scales both edges together so the locked ratio survives', () => {
+ expect(
+ resolveOutputSize(
+ { height: 500, width: 1000 },
+ { edited: 'height', height: MAX_OUTPUT_EDGE, width: 0 },
+ true,
+ ),
+ ).toEqual({ height: MAX_OUTPUT_EDGE / 2, width: MAX_OUTPUT_EDGE });
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Resize/crop.ts b/src/features/FileViewer/Renderer/Image/Tools/Resize/crop.ts
new file mode 100644
index 00000000000..e57b59a40ce
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Resize/crop.ts
@@ -0,0 +1,128 @@
+import { clamp, type NormalizedRect, type Size } from '../../geometry';
+
+export type AspectPreset = 'free' | 'original' | '1:1' | '4:3' | '3:4' | '16:9' | '9:16';
+
+export const ASPECT_PRESETS: AspectPreset[] = [
+ 'free',
+ 'original',
+ '1:1',
+ '4:3',
+ '3:4',
+ '16:9',
+ '9:16',
+];
+
+/** Largest output edge we will render, to keep the canvas inside browser limits. */
+export const MAX_OUTPUT_EDGE = 8192;
+
+/** Smallest crop edge, as a fraction of the image, so handles never collapse. */
+const MIN_CROP = 0.02;
+
+/** Pixel aspect (width / height) for a preset, or `undefined` when unconstrained. */
+export const aspectRatioOf = (preset: AspectPreset, natural: Size): number | undefined => {
+ if (preset === 'free') return undefined;
+ if (preset === 'original') return natural.width / natural.height;
+ const [w, h] = preset.split(':').map(Number);
+ return w / h;
+};
+
+/** The largest centered crop with the given pixel aspect. */
+export const centeredCrop = (natural: Size, aspect: number | undefined): NormalizedRect => {
+ if (!aspect) return { height: 1, width: 1, x: 0, y: 0 };
+
+ const imageAspect = natural.width / natural.height;
+ if (aspect > imageAspect) {
+ const height = imageAspect / aspect;
+ return { height, width: 1, x: 0, y: (1 - height) / 2 };
+ }
+ const width = aspect / imageAspect;
+ return { height: 1, width, x: (1 - width) / 2, y: 0 };
+};
+
+export type CropHandle = 'move' | 'nw' | 'ne' | 'sw' | 'se';
+
+/**
+ * Apply a drag delta (normalized) to a crop rect. Corners resize against the
+ * opposite, fixed corner; with a locked aspect the axis the pointer moved
+ * more along (in pixels) drives the other. The result always stays inside the
+ * image.
+ */
+export const dragCrop = (
+ start: NormalizedRect,
+ handle: CropHandle,
+ delta: { x: number; y: number },
+ natural: Size,
+ aspect?: number,
+): NormalizedRect => {
+ if (handle === 'move') {
+ return {
+ ...start,
+ x: clamp(start.x + delta.x, 0, 1 - start.width),
+ y: clamp(start.y + delta.y, 0, 1 - start.height),
+ };
+ }
+
+ const west = handle === 'nw' || handle === 'sw';
+ const north = handle === 'nw' || handle === 'ne';
+ const anchorX = west ? start.x + start.width : start.x;
+ const anchorY = north ? start.y + start.height : start.y;
+
+ const maxWidth = west ? anchorX : 1 - anchorX;
+ const maxHeight = north ? anchorY : 1 - anchorY;
+
+ let width = clamp(start.width + (west ? -delta.x : delta.x), MIN_CROP, maxWidth);
+ let height = clamp(start.height + (north ? -delta.y : delta.y), MIN_CROP, maxHeight);
+
+ if (aspect) {
+ // Normalized height for a normalized width at this pixel aspect.
+ const ratio = natural.width / natural.height / aspect;
+ const vertical = Math.abs(delta.y * natural.height) > Math.abs(delta.x * natural.width);
+ if (vertical) width = clamp(height / ratio, MIN_CROP, maxWidth);
+ height = width * ratio;
+ if (height > maxHeight) {
+ height = maxHeight;
+ width = height / ratio;
+ }
+ }
+
+ return {
+ height,
+ width,
+ x: west ? anchorX - width : anchorX,
+ y: north ? anchorY - height : anchorY,
+ };
+};
+
+/** Pixel size of a crop at the image's natural resolution. */
+export const cropPixelSize = (crop: NormalizedRect, natural: Size): Size => {
+ const height = crop.height * natural.height;
+ const width = crop.width * natural.width;
+ // Scale a huge crop down to the output cap so the export canvas stays allocatable.
+ const scale = Math.min(1, MAX_OUTPUT_EDGE / Math.max(height, width, 1));
+ return {
+ height: Math.max(1, Math.round(height * scale)),
+ width: Math.max(1, Math.round(width * scale)),
+ };
+};
+
+/**
+ * Resolve the output size from the user's width/height entry. With the ratio
+ * locked, the edited side wins and the other follows the crop's aspect.
+ */
+export const resolveOutputSize = (
+ crop: Size,
+ input: { edited: 'height' | 'width'; height: number; width: number },
+ locked: boolean,
+): Size => {
+ const safe = (value: number) => clamp(Math.round(value) || 1, 1, MAX_OUTPUT_EDGE);
+ if (!locked) return { height: safe(input.height), width: safe(input.width) };
+
+ const aspect = crop.width / crop.height;
+ const raw =
+ input.edited === 'width'
+ ? { height: (Math.round(input.width) || 1) / aspect, width: Math.round(input.width) || 1 }
+ : { height: Math.round(input.height) || 1, width: (Math.round(input.height) || 1) * aspect };
+ // Scale both edges together at the cap so the locked ratio survives.
+ const fit = Math.min(1, MAX_OUTPUT_EDGE / Math.max(raw.height, raw.width));
+ return { height: safe(raw.height * fit), width: safe(raw.width * fit) };
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/Resize/index.tsx b/src/features/FileViewer/Renderer/Image/Tools/Resize/index.tsx
new file mode 100644
index 00000000000..2bd5858e0eb
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/Resize/index.tsx
@@ -0,0 +1,299 @@
+'use client';
+
+import { ActionIcon, Input, Select } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { LinkIcon, SaveIcon, UnlinkIcon, XIcon } from 'lucide-react';
+import type { PointerEvent } from 'react';
+import { useRef, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { useTranslation } from 'react-i18next';
+
+import { useImageStage } from '../../context';
+import type { NormalizedRect, Point, Size } from '../../geometry';
+import BarButton from '../BarButton';
+import { renderImageToBlob } from '../exportImage';
+import { toolStyles } from '../styles';
+import { useSaveDerivedImage } from '../useSaveDerivedImage';
+import { useToolKeys } from '../useToolKeys';
+import {
+ ASPECT_PRESETS,
+ type AspectPreset,
+ aspectRatioOf,
+ centeredCrop,
+ type CropHandle,
+ cropPixelSize,
+ dragCrop,
+ MAX_OUTPUT_EDGE,
+ resolveOutputSize,
+} from './crop';
+
+const styles = createStaticStyles(({ css }) => ({
+ box: css`
+ cursor: move;
+ position: absolute;
+ border: 1px solid #fff;
+ box-shadow: 0 0 0 9999px rgb(0 0 0 / 45%);
+
+ &::before,
+ &::after {
+ pointer-events: none;
+ content: '';
+ position: absolute;
+ border: 0 dashed rgb(255 255 255 / 60%);
+ }
+
+ &::before {
+ inset-block: 0;
+ inset-inline: 33.33%;
+ border-inline-width: 1px;
+ }
+
+ &::after {
+ inset-block: 33.33%;
+ inset-inline: 0;
+ border-block-width: 1px;
+ }
+ `,
+ clip: css`
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+ `,
+ handle: css`
+ position: absolute;
+ z-index: 1;
+
+ width: 14px;
+ height: 14px;
+ border: 2px solid ${cssVar.colorPrimary};
+ border-radius: 3px;
+
+ background: #fff;
+ `,
+ sizeInput: css`
+ flex-shrink: 0;
+ width: 84px;
+
+ &[data-compact='true'] {
+ width: 72px;
+ }
+ `,
+}));
+
+// Handles sit just inside the crop corners so they stay grabbable when the
+// crop reaches the image edge (the layer clips anything outside the image).
+const HANDLES: { cursor: string; handle: Exclude<CropHandle, 'move'>; x: string; y: string }[] = [
+ { cursor: 'nwse-resize', handle: 'nw', x: '-1px', y: '-1px' },
+ { cursor: 'nesw-resize', handle: 'ne', x: 'calc(100% - 13px)', y: '-1px' },
+ { cursor: 'nesw-resize', handle: 'sw', x: '-1px', y: 'calc(100% - 13px)' },
+ { cursor: 'nwse-resize', handle: 'se', x: 'calc(100% - 13px)', y: 'calc(100% - 13px)' },
+];
+
+interface ResizeModeProps {
+ onExit: () => void;
+}
+
+/**
+ * Crop to a region (free or a preset ratio) and scale to an exact pixel size,
+ * then save the result as a new file.
+ */
+const ResizeMode = ({ onExit }: ResizeModeProps) => {
+ const { t } = useTranslation('file');
+ const { compact, naturalSize, overlayElement, toImagePoint } = useImageStage();
+ const natural: Size = naturalSize ?? { height: 1, width: 1 };
+
+ const [preset, setPreset] = useState<AspectPreset>('free');
+ const [crop, setCropState] = useState<NormalizedRect>(() => centeredCrop(natural, undefined));
+ const [output, setOutput] = useState<Size>(() => cropPixelSize(crop, natural));
+ const [locked, setLocked] = useState(true);
+ // What the user is typing, so a field can be emptied mid-edit.
+ const [typing, setTyping] = useState<{ side: 'height' | 'width'; text: string } | null>(null);
+ const drag = useRef<{ handle: CropHandle; point: Point; start: NormalizedRect } | null>(null);
+ const { save, saving } = useSaveDerivedImage('resize');
+
+ const aspect = aspectRatioOf(preset, natural);
+
+ // A new crop resets the output to the crop's own pixel size.
+ const setCrop = (next: NormalizedRect) => {
+ setCropState(next);
+ setOutput(cropPixelSize(next, natural));
+ setTyping(null);
+ };
+
+ const handleSave = async () => {
+ const result = await save((img) => renderImageToBlob(img, { crop, output }));
+ if (result) onExit();
+ };
+
+ // While saving, Enter would start a duplicate upload and Escape would hide
+ // an upload that still lands; the shortcuts wait for the save to finish.
+ useToolKeys({
+ onEnter: saving ? undefined : () => void handleSave(),
+ onEscape: saving ? undefined : onExit,
+ });
+
+ const startDrag = (handle: CropHandle) => (event: PointerEvent<HTMLElement>) => {
+ if (event.button !== 0) return;
+ event.stopPropagation();
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ drag.current = { handle, point, start: crop };
+ };
+
+ const moveDrag = (event: PointerEvent<HTMLElement>) => {
+ const state = drag.current;
+ if (!state) return;
+ const point = toImagePoint({ x: event.clientX, y: event.clientY });
+ if (!point) return;
+ setCrop(
+ dragCrop(
+ state.start,
+ state.handle,
+ { x: point.x - state.point.x, y: point.y - state.point.y },
+ natural,
+ aspect,
+ ),
+ );
+ };
+
+ const endDrag = () => {
+ drag.current = null;
+ };
+
+ const cropSize = cropPixelSize(crop, natural);
+
+ const updateOutput = (edited: 'height' | 'width', value: string) => {
+ setTyping({ side: edited, text: value });
+ const numeric = Number(value);
+ if (!value || !Number.isFinite(numeric) || numeric <= 0) return;
+ setOutput(resolveOutputSize(cropSize, { ...output, [edited]: numeric, edited }, locked));
+ };
+
+ return (
+ <>
+ {overlayElement &&
+ createPortal(
+ <div
+ className={styles.clip}
+ data-testid={'image-resize-layer'}
+ onPointerDown={(event) => event.stopPropagation()}
+ >
+ <div
+ aria-label={`${cropSize.width} × ${cropSize.height}`}
+ className={styles.box}
+ data-testid={'image-crop-box'}
+ role={'group'}
+ style={{
+ height: `${crop.height * 100}%`,
+ left: `${crop.x * 100}%`,
+ top: `${crop.y * 100}%`,
+ touchAction: 'none',
+ width: `${crop.width * 100}%`,
+ }}
+ onPointerCancel={endDrag}
+ onPointerDown={startDrag('move')}
+ onPointerMove={moveDrag}
+ onPointerUp={endDrag}
+ >
+ {HANDLES.map(({ cursor, handle, x, y }) => (
+ <span
+ className={styles.handle}
+ data-handle={handle}
+ key={handle}
+ style={{ cursor, left: x, top: y, touchAction: 'none' }}
+ onPointerCancel={endDrag}
+ onPointerDown={startDrag(handle)}
+ onPointerMove={moveDrag}
+ onPointerUp={endDrag}
+ />
+ ))}
+ </div>
+ </div>,
+ overlayElement,
+ )}
+ <div className={toolStyles.dock}>
+ <div aria-label={t('imageViewer.tool.resize')} className={toolStyles.bar} role={'toolbar'}>
+ <Select
+ aria-label={t('imageViewer.resize.aspectLabel')}
+ prefix={compact ? undefined : t('imageViewer.resize.aspectLabel')}
+ size={'small'}
+ style={{ flexShrink: 0, width: compact ? 88 : 150 }}
+ value={preset}
+ options={ASPECT_PRESETS.map((value) => ({
+ label:
+ value === 'free' || value === 'original'
+ ? t(`imageViewer.resize.aspect.${value}`)
+ : value,
+ value,
+ }))}
+ onChange={(value) => {
+ const next = value as AspectPreset;
+ setPreset(next);
+ setCrop(centeredCrop(natural, aspectRatioOf(next, natural)));
+ }}
+ />
+ <span className={toolStyles.divider} />
+ <Input
+ aria-label={t('imageViewer.resize.width')}
+ className={styles.sizeInput}
+ data-compact={compact}
+ inputMode={'numeric'}
+ max={MAX_OUTPUT_EDGE}
+ min={1}
+ prefix={'W'}
+ size={'small'}
+ type={'number'}
+ value={typing?.side === 'width' ? typing.text : output.width}
+ onBlur={() => setTyping(null)}
+ onChange={(event) => updateOutput('width', event.target.value)}
+ />
+ <ActionIcon
+ active={locked}
+ aria-label={t('imageViewer.resize.lock')}
+ aria-pressed={locked}
+ icon={locked ? LinkIcon : UnlinkIcon}
+ size={'small'}
+ title={t('imageViewer.resize.lock')}
+ onClick={() => {
+ const next = !locked;
+ setLocked(next);
+ if (next)
+ setOutput(resolveOutputSize(cropSize, { ...output, edited: 'width' }, true));
+ }}
+ />
+ <Input
+ aria-label={t('imageViewer.resize.height')}
+ className={styles.sizeInput}
+ data-compact={compact}
+ inputMode={'numeric'}
+ max={MAX_OUTPUT_EDGE}
+ min={1}
+ prefix={'H'}
+ size={'small'}
+ type={'number'}
+ value={typing?.side === 'height' ? typing.text : output.height}
+ onBlur={() => setTyping(null)}
+ onChange={(event) => updateOutput('height', event.target.value)}
+ />
+ <span className={toolStyles.divider} />
+ <BarButton
+ disabled={saving}
+ icon={XIcon}
+ label={t('imageViewer.cancel')}
+ onClick={onExit}
+ />
+ <BarButton
+ icon={SaveIcon}
+ label={saving ? t('imageViewer.saving') : t('imageViewer.saveAsNew')}
+ loading={saving}
+ type={'primary'}
+ onClick={() => void handleSave()}
+ />
+ </div>
+ </div>
+ </>
+ );
+};
+
+export default ResizeMode;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/SendToChatButton.tsx b/src/features/FileViewer/Renderer/Image/Tools/SendToChatButton.tsx
new file mode 100644
index 00000000000..0a265fcb496
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/SendToChatButton.tsx
@@ -0,0 +1,45 @@
+'use client';
+
+import { MessageSquareShareIcon } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import BarButton from './BarButton';
+import { type ImageMarkup, isMarkupEmpty } from './markup';
+import { useSendMarkupToChat } from './useSendMarkupToChat';
+
+interface SendToChatButtonProps {
+ markup: ImageMarkup;
+ /** Commit anything still being edited and return the marks to send. */
+ onBeforeSend?: () => ImageMarkup;
+ /** Called with the marks that went into the chat input, so only those are cleared. */
+ onSent: (sent: ImageMarkup) => void;
+}
+
+/**
+ * Primary action of annotate and comment: put the marked-up image and the
+ * numbered comments into the chat input. Without a conversation next to the
+ * viewer, it starts one with the inbox agent instead.
+ */
+const SendToChatButton = ({ markup, onBeforeSend, onSent }: SendToChatButtonProps) => {
+ const { t } = useTranslation('file');
+ const { hasComposer, send, sending } = useSendMarkupToChat();
+ const empty = isMarkupEmpty(markup);
+
+ return (
+ <BarButton
+ data-testid={'image-markup-send'}
+ disabled={empty}
+ icon={MessageSquareShareIcon}
+ label={t(hasComposer ? 'imageViewer.markup.addToChat' : 'imageViewer.markup.askInNewChat')}
+ loading={sending}
+ title={empty ? t('imageViewer.markup.empty') : undefined}
+ type={'primary'}
+ onClick={async () => {
+ const toSend = onBeforeSend?.() ?? markup;
+ if (await send(toSend)) onSent(toSend);
+ }}
+ />
+ );
+};
+
+export default SendToChatButton;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/exportImage.test.ts b/src/features/FileViewer/Renderer/Image/Tools/exportImage.test.ts
new file mode 100644
index 00000000000..171750d6bf6
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/exportImage.test.ts
@@ -0,0 +1,225 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ImagePixelsUnavailableError, loadReadableImage, renderImageToBlob } from './exportImage';
+
+const createCtx = () => ({
+ arc: vi.fn(),
+ beginPath: vi.fn(),
+ fill: vi.fn(),
+ fillText: vi.fn(),
+ drawImage: vi.fn(),
+ imageSmoothingQuality: 'low',
+ lineTo: vi.fn(),
+ moveTo: vi.fn(),
+ restore: vi.fn(),
+ save: vi.fn(),
+ setLineDash: vi.fn(),
+ setTransform: vi.fn(),
+ stroke: vi.fn(),
+ strokeRect: vi.fn(),
+});
+
+const source = { naturalHeight: 1000, naturalWidth: 2000 } as unknown as HTMLImageElement;
+
+describe('renderImageToBlob', () => {
+ let ctx: ReturnType<typeof createCtx>;
+ let canvases: HTMLCanvasElement[];
+ let tainted: boolean;
+
+ beforeEach(() => {
+ ctx = createCtx();
+ canvases = [];
+ tainted = false;
+ const create = document.createElement.bind(document);
+ vi.spyOn(document, 'createElement').mockImplementation(((tag: string) => {
+ const element = create(tag);
+ if (tag === 'canvas') {
+ const canvas = element as HTMLCanvasElement;
+ canvas.getContext = vi.fn(() => ctx) as never;
+ canvas.toBlob = vi.fn((callback: BlobCallback, type?: string) => {
+ if (tainted)
+ throw new DOMException('Tainted canvases may not be exported.', 'SecurityError');
+ callback(new Blob(['png'], { type }));
+ }) as never;
+ canvases.push(canvas);
+ }
+ return element;
+ }) as typeof document.createElement);
+ });
+
+ afterEach(() => vi.restoreAllMocks());
+
+ it('exports the full image at natural size by default', async () => {
+ const blob = await renderImageToBlob(source);
+
+ expect(blob.type).toBe('image/png');
+ expect(canvases[0].width).toBe(2000);
+ expect(canvases[0].height).toBe(1000);
+ expect(ctx.drawImage).toHaveBeenCalledWith(source, 0, 0, 2000, 1000, 0, 0, 2000, 1000);
+ expect(ctx.strokeRect).not.toHaveBeenCalled();
+ });
+
+ // Regression: annotate/erase exports allocated a full-resolution canvas,
+ // which a very large image can push past the browser's limits.
+ it('caps an export without an explicit size at the default max edge', async () => {
+ const huge = { naturalHeight: 6000, naturalWidth: 12_000 } as unknown as HTMLImageElement;
+ await renderImageToBlob(huge);
+
+ expect(canvases[0].width).toBe(4096);
+ expect(canvases[0].height).toBe(2048);
+ });
+
+ it('crops and scales to the requested output size', async () => {
+ await renderImageToBlob(source, {
+ crop: { height: 0.5, width: 0.25, x: 0.5, y: 0.25 },
+ output: { height: 250, width: 250 },
+ });
+
+ expect(canvases[0].width).toBe(250);
+ expect(ctx.drawImage).toHaveBeenCalledWith(source, 1000, 250, 500, 500, 0, 0, 250, 250);
+ });
+
+ it('burns annotations into the exported pixels', async () => {
+ await renderImageToBlob(source, {
+ shapes: [
+ {
+ color: '#f00',
+ rect: { height: 0.1, width: 0.1, x: 0.1, y: 0.1 },
+ size: 0.01,
+ type: 'rect',
+ },
+ ],
+ });
+
+ expect(ctx.setTransform).toHaveBeenCalledWith(1, 0, 0, 1, -0, -0);
+ expect(ctx.strokeRect).toHaveBeenCalledWith(200, 100, 200, 100);
+ });
+
+ it('burns numbered comment markers into the exported pixels', async () => {
+ await renderImageToBlob(source, {
+ comments: [
+ { anchor: { point: { x: 0.5, y: 0.5 }, type: 'point' }, id: 'a', text: 'here' },
+ {
+ anchor: { rect: { height: 0.2, width: 0.1, x: 0.1, y: 0.1 }, type: 'region' },
+ id: 'b',
+ text: 'there',
+ },
+ ],
+ });
+
+ expect(ctx.fillText).toHaveBeenNthCalledWith(1, '1', 1000, 500);
+ expect(ctx.fillText).toHaveBeenNthCalledWith(2, '2', 200, 100);
+ // A region also gets its outline.
+ expect(ctx.strokeRect).toHaveBeenCalledWith(200, 100, 200, 200);
+ });
+
+ it('reports unreadable pixels when the canvas is tainted', async () => {
+ tainted = true;
+
+ await expect(renderImageToBlob(source)).rejects.toBeInstanceOf(ImagePixelsUnavailableError);
+ });
+});
+
+describe('loadReadableImage', () => {
+ class FakeImage extends EventTarget {
+ decoding = '';
+ naturalHeight = 800;
+ naturalWidth = 1200;
+ set src(value: string) {
+ this.loaded = value;
+ queueMicrotask(() => this.dispatchEvent(new Event('load')));
+ }
+ loaded = '';
+ }
+
+ beforeEach(() => {
+ vi.stubGlobal('Image', FakeImage);
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:local/1');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+ });
+
+ // Regression: the viewer shows the image without CORS first, so the HTTP
+ // cache holds a response without Access-Control-Allow-Origin. Reading the
+ // pixels must bypass that cached entry or every export fails.
+ it('reads storage bytes past the HTTP cache and decodes them from a blob URL', async () => {
+ const fetchMock = vi.fn(async () => new Response(new Blob(['png'], { type: 'image/png' })));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const img = (await loadReadableImage('https://s3/a.png?sig=1')) as unknown as FakeImage;
+
+ expect(fetchMock).toHaveBeenCalledWith('https://s3/a.png?sig=1', {
+ cache: 'no-store',
+ credentials: 'omit',
+ mode: 'cors',
+ });
+ expect(img.loaded).toBe('blob:local/1');
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:local/1');
+ });
+
+ // Regression: production files are `/f/:id` proxy URLs that redirect to
+ // storage; a cross-origin redirect nulls the Origin so CORS always fails.
+ it('reads a /f/:id proxy file from the storage URL behind it', async () => {
+ const fetchMock = vi.fn(async () => new Response(new Blob(['png'], { type: 'image/png' })));
+ vi.stubGlobal('fetch', fetchMock);
+ const resolveProxyUrl = vi.fn(async () => 'https://s3/files/a.png?sig=2');
+
+ await loadReadableImage('https://app.lobehub.com/f/file_abc', { resolveProxyUrl });
+
+ expect(resolveProxyUrl).toHaveBeenCalledWith('file_abc');
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://s3/files/a.png?sig=2',
+ expect.objectContaining({ mode: 'cors' }),
+ );
+ });
+
+ it('fetches other URLs as they are', async () => {
+ const fetchMock = vi.fn(async () => new Response(new Blob(['png'], { type: 'image/png' })));
+ vi.stubGlobal('fetch', fetchMock);
+ const resolveProxyUrl = vi.fn();
+
+ await loadReadableImage('https://s3/f/file_abc/a.png', { resolveProxyUrl });
+
+ expect(resolveProxyUrl).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledWith('https://s3/f/file_abc/a.png', expect.anything());
+ });
+
+ it('reports pixels as unavailable when the storage URL cannot be resolved', async () => {
+ vi.stubGlobal('fetch', vi.fn());
+ const resolveProxyUrl = vi.fn(async () => {
+ throw new Error('NOT_FOUND');
+ });
+
+ await expect(loadReadableImage('/f/file_abc', { resolveProxyUrl })).rejects.toBeInstanceOf(
+ ImagePixelsUnavailableError,
+ );
+ });
+
+ it('reports unreadable pixels when storage refuses the CORS request', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('Failed to fetch');
+ }),
+ );
+
+ await expect(loadReadableImage('https://s3/a.png')).rejects.toBeInstanceOf(
+ ImagePixelsUnavailableError,
+ );
+ });
+
+ it('loads blob URLs directly', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+
+ await loadReadableImage('blob:local/upload');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/exportImage.ts b/src/features/FileViewer/Renderer/Image/Tools/exportImage.ts
new file mode 100644
index 00000000000..e9fe054760a
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/exportImage.ts
@@ -0,0 +1,172 @@
+import type { NormalizedRect, Size } from '../geometry';
+import { type AnnotationShape, drawShapes } from './Annotate/shapes';
+import { drawCommentMarkers, type MarkupComment } from './markup';
+
+export class ImagePixelsUnavailableError extends Error {
+ constructor(cause?: unknown) {
+ super('Image pixels are not readable from this origin');
+ this.name = 'ImagePixelsUnavailableError';
+ this.cause = cause;
+ }
+}
+
+const loadImage = (src: string) =>
+ new Promise<HTMLImageElement>((resolve, reject) => {
+ const img = new Image();
+ img.decoding = 'async';
+ img.addEventListener('load', () => resolve(img));
+ img.addEventListener('error', () => reject(new Error(`Failed to load image: ${src}`)));
+ img.src = src;
+ });
+
+const FILE_PROXY_PATH = /^\/f\/([^/]+)$/;
+
+/** File id of a `/f/:id` proxy URL, whatever host serves it. */
+export const fileIdFromProxyUrl = (src: string): string | undefined => {
+ try {
+ const match = new URL(src, globalThis.location?.href).pathname.match(FILE_PROXY_PATH);
+ return match ? decodeURIComponent(match[1]) : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+export interface LoadReadableImageOptions {
+ /**
+ * Resolve a `/f/:id` proxy URL to the storage URL behind it. The proxy
+ * answers with a cross-origin redirect, which turns the request's Origin into
+ * `null`, so no bucket CORS rule can allow reading it.
+ */
+ resolveProxyUrl?: (fileId: string) => Promise<string>;
+}
+
+/**
+ * Load an image whose pixels a canvas may read. Storage URLs are cross-origin
+ * and the viewer has usually displayed them already without CORS, so the HTTP
+ * cache may hold a response with no `Access-Control-Allow-Origin`; reading the
+ * bytes with `cache: 'no-store'` sidesteps that entry. Blob and data URLs are
+ * same-origin and load directly.
+ */
+export const loadReadableImage = async (
+ src: string,
+ { resolveProxyUrl }: LoadReadableImageOptions = {},
+): Promise<HTMLImageElement> => {
+ if (src.startsWith('blob:') || src.startsWith('data:')) return loadImage(src);
+
+ let blob: Blob;
+ try {
+ const proxiedFileId = resolveProxyUrl ? fileIdFromProxyUrl(src) : undefined;
+ const readableUrl = proxiedFileId ? await resolveProxyUrl!(proxiedFileId) : src;
+ const response = await fetch(readableUrl, {
+ cache: 'no-store',
+ credentials: 'omit',
+ mode: 'cors',
+ });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ blob = await response.blob();
+ } catch (error) {
+ throw new ImagePixelsUnavailableError(error);
+ }
+
+ const blobUrl = URL.createObjectURL(blob);
+ try {
+ return await loadImage(blobUrl);
+ } finally {
+ // The decoded image keeps its pixels; the blob URL is no longer needed.
+ URL.revokeObjectURL(blobUrl);
+ }
+};
+
+/**
+ * Longest edge of an export without an explicit output size (annotations for
+ * chat, the erase guide). Large enough for a model to read, small enough that
+ * the canvas stays allocatable on any image.
+ */
+export const DEFAULT_EXPORT_MAX_EDGE = 4096;
+
+export interface RenderImageOptions {
+ /** Numbered comment markers, in the source's normalized space. */
+ comments?: MarkupComment[];
+ /** Region of the source to keep; defaults to the whole image. */
+ crop?: NormalizedRect;
+ /**
+ * Output pixel size; defaults to the cropped region at natural resolution,
+ * scaled down to `DEFAULT_EXPORT_MAX_EDGE` on its longer side.
+ */
+ output?: Size;
+ /** Annotations drawn in the source's normalized space. */
+ shapes?: AnnotationShape[];
+ type?: 'image/png' | 'image/jpeg' | 'image/webp';
+}
+
+/**
+ * Render the source image (optionally cropped, scaled, annotated and marked
+ * with numbered comments) into a
+ * new PNG blob. The original file is never touched.
+ */
+export const renderImageToBlob = (
+ img: CanvasImageSource & { naturalHeight: number; naturalWidth: number },
+ {
+ comments = [],
+ crop = { height: 1, width: 1, x: 0, y: 0 },
+ output,
+ shapes = [],
+ type = 'image/png',
+ }: RenderImageOptions = {},
+): Promise<Blob> => {
+ const natural = { height: img.naturalHeight, width: img.naturalWidth };
+ const source = {
+ height: crop.height * natural.height,
+ width: crop.width * natural.width,
+ x: crop.x * natural.width,
+ y: crop.y * natural.height,
+ };
+ const fit = Math.min(1, DEFAULT_EXPORT_MAX_EDGE / Math.max(source.height, source.width, 1));
+ const size = output ?? {
+ height: Math.max(1, Math.round(source.height * fit)),
+ width: Math.max(1, Math.round(source.width * fit)),
+ };
+
+ const canvas = document.createElement('canvas');
+ canvas.width = size.width;
+ canvas.height = size.height;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return Promise.reject(new Error('Canvas 2D context is unavailable'));
+
+ ctx.imageSmoothingQuality = 'high';
+ ctx.drawImage(
+ img,
+ source.x,
+ source.y,
+ source.width,
+ source.height,
+ 0,
+ 0,
+ size.width,
+ size.height,
+ );
+
+ if (shapes.length > 0 || comments.length > 0) {
+ // Shapes are normalized to the full image; draw them in full-image pixel
+ // space and shift/scale so the crop window lands on the canvas.
+ const scaleX = size.width / source.width;
+ const scaleY = size.height / source.height;
+ ctx.save();
+ ctx.setTransform(scaleX, 0, 0, scaleY, -source.x * scaleX, -source.y * scaleY);
+ drawShapes(ctx, shapes, natural.width, natural.height);
+ drawCommentMarkers(ctx, comments, natural.width, natural.height);
+ ctx.restore();
+ }
+
+ return new Promise<Blob>((resolve, reject) => {
+ try {
+ canvas.toBlob((blob) => {
+ if (blob) resolve(blob);
+ else reject(new Error('Canvas export produced no data'));
+ }, type);
+ } catch (error) {
+ // A tainted canvas throws SecurityError synchronously.
+ reject(new ImagePixelsUnavailableError(error));
+ }
+ });
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx b/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx
new file mode 100644
index 00000000000..4c3e724a142
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/index.test.tsx
@@ -0,0 +1,719 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { useState } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useComposerDraftBus } from '@/features/Conversation/composerDraftBus';
+
+import { ImageStageContext, type ImageStageValue } from '../context';
+import { clientToImagePoint, type Point } from '../geometry';
+import ImageEditTools from './index';
+import { EMPTY_MARKUP, type ImageMarkup } from './markup';
+
+const fileStore = vi.hoisted(() => ({
+ chatUploadFileList: [] as { error?: string; file: File; id: string; status: string }[],
+ dispatchChatUploadFileList: vi.fn(),
+ refreshFileList: vi.fn(),
+ uploadChatFiles: vi.fn(),
+ uploadWithProgress: vi.fn(),
+}));
+vi.mock('@/store/file', () => ({
+ fileManagerSelectors: {
+ getFileByChunkTargetId: () => () => ({ id: 'file_src', parentId: 'docs_folder' }),
+ },
+ useFileStore: { getState: () => fileStore },
+}));
+
+const chatState = vi.hoisted(() => ({ activeAgentId: 'agt_current', activeTopicId: 'tpc_1' }));
+vi.mock('@/store/chat', () => ({
+ useChatStore: { getState: () => chatState },
+}));
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (s: unknown) => unknown) => selector({}),
+}));
+vi.mock('@/store/agent/selectors', () => ({
+ builtinAgentSelectors: { inboxAgentId: () => 'agt_inbox' },
+}));
+
+const permission = vi.hoisted(() => ({ allowed: true, reason: undefined as string | undefined }));
+vi.mock('@/hooks/usePermission', () => ({ usePermission: () => permission }));
+
+const navigate = vi.hoisted(() => vi.fn());
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => navigate,
+}));
+
+const exporter = vi.hoisted(() => ({
+ loadStageImage: vi.fn(),
+ renderImageToBlob: vi.fn(),
+}));
+vi.mock('./exportImage', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ renderImageToBlob: exporter.renderImageToBlob,
+}));
+
+const location = vi.hoisted(() => ({
+ addToKnowledgeBase: vi.fn(),
+ getFile: vi.fn(),
+}));
+vi.mock('./AIEdit/deps', async (importOriginal) => {
+ const { aiEditDeps } = await importOriginal<{ aiEditDeps: object }>();
+ return { aiEditDeps: { ...aiEditDeps, ...location }, loadStageImage: exporter.loadStageImage };
+});
+
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast,
+}));
+
+// The displayed image box: 200×100 at the page origin.
+const RECT = { bottom: 100, height: 100, left: 0, right: 200, top: 0, width: 200, x: 0, y: 0 };
+
+const renderTools = (stage: Partial<ImageStageValue> = {}) => {
+ const overlay = document.createElement('div');
+ overlay.getBoundingClientRect = () => RECT as DOMRect;
+ document.body.append(overlay);
+ const fitToScreen = vi.fn();
+ const addVersion = vi.fn();
+ const value: ImageStageValue = {
+ addVersion,
+ fileId: 'file_src',
+ compact: false,
+ fitToScreen,
+ markup: EMPTY_MARKUP,
+ name: 'sunset.jpg',
+ naturalSize: { height: 1000, width: 2000 },
+ overlayElement: overlay,
+ rotation: 0,
+ setBusy: () => {},
+ setMarkup: () => {},
+ setReserve: () => {},
+ toImagePoint: (client) => clientToImagePoint(client, RECT, 0),
+ url: 'https://s3/sunset.jpg',
+ zoom: 1,
+ ...stage,
+ };
+ // Marks live in the viewer; this stands in for it.
+ const Wrapper = ({ children }: { children: ReactNode }) => {
+ const [markup, setMarkup] = useState<ImageMarkup>(EMPTY_MARKUP);
+ return (
+ <ImageStageContext value={{ ...value, markup, setMarkup }}>{children}</ImageStageContext>
+ );
+ };
+ // Tool shortcuts only listen inside the viewer.
+ const viewer = document.createElement('div');
+ viewer.dataset.testid = 'image-viewer';
+ document.body.append(viewer);
+ return {
+ addVersion,
+ fitToScreen,
+ overlay,
+ ...render(<ImageEditTools />, { container: viewer, wrapper: Wrapper }),
+ };
+};
+
+describe('ImageEditTools', () => {
+ beforeEach(() => {
+ useComposerDraftBus.setState({ attached: true, draft: null });
+ fileStore.chatUploadFileList = [];
+ chatState.activeTopicId = 'tpc_1';
+ permission.allowed = true;
+ permission.reason = undefined;
+ fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
+ });
+ exporter.loadStageImage.mockResolvedValue({ naturalHeight: 1000, naturalWidth: 2000 });
+ exporter.renderImageToBlob.mockResolvedValue(new Blob(['png'], { type: 'image/png' }));
+ fileStore.uploadWithProgress.mockResolvedValue({ id: 'file_new', url: 'files/new.png' });
+ location.addToKnowledgeBase.mockResolvedValue(undefined);
+ location.getFile.mockResolvedValue({ knowledgeBaseIds: ['kb_1'], parentId: 'docs_folder' });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ document.body.innerHTML = '';
+ });
+
+ it('shows annotate, comment and resize in the floating toolbar', () => {
+ renderTools();
+
+ const toolbar = screen.getByRole('toolbar', { name: 'imageViewer.editTools' });
+ expect(within(toolbar).getByText('imageViewer.tool.annotate')).toBeInTheDocument();
+ expect(within(toolbar).getByText('imageViewer.tool.comment')).toBeInTheDocument();
+ expect(within(toolbar).getByText('imageViewer.tool.resize')).toBeInTheDocument();
+ // Nothing to send until something is marked.
+ expect(screen.queryByTestId('image-markup-send')).not.toBeInTheDocument();
+ });
+
+ const addComment = (overlay: HTMLElement, text: string, from: Point, to: Point = from) => {
+ const layer = within(overlay).getByTestId('image-comment-layer');
+ layer.setPointerCapture = vi.fn();
+ fireEvent.pointerDown(layer, { button: 0, clientX: from.x, clientY: from.y, pointerId: 1 });
+ fireEvent.pointerMove(layer, { clientX: to.x, clientY: to.y, pointerId: 1 });
+ fireEvent.pointerUp(layer, { clientX: to.x, clientY: to.y, pointerId: 1 });
+ const input = within(overlay).getByRole('textbox', { name: 'imageViewer.comment.add' });
+ fireEvent.change(input, { target: { value: text } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+ };
+
+ const drawBox = (overlay: HTMLElement) => {
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.annotate.rect' }));
+ const canvas = within(overlay).getByTestId('image-annotate-canvas');
+ canvas.setPointerCapture = vi.fn();
+ fireEvent.pointerDown(canvas, { button: 0, clientX: 20, clientY: 10, pointerId: 1 });
+ fireEvent.pointerMove(canvas, { clientX: 120, clientY: 60, pointerId: 1 });
+ fireEvent.pointerUp(canvas, { pointerId: 1 });
+ };
+
+ describe('comments', () => {
+ it('pins a comment at a clicked point and another on a dragged region', () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ expect(screen.getByText('imageViewer.comment.empty')).toBeInTheDocument();
+
+ addComment(overlay, 'Too dark here', { x: 50, y: 75 });
+ addComment(overlay, 'Remove this', { x: 100, y: 20 }, { x: 160, y: 80 });
+
+ const panel = screen.getByTestId('image-comment-panel');
+ expect(within(panel).getByText('Too dark here')).toBeInTheDocument();
+ expect(within(panel).getByText('Remove this')).toBeInTheDocument();
+ const pins = within(overlay).getAllByRole('button', { name: 'imageViewer.comment.pin' });
+ expect(pins).toHaveLength(2);
+ expect(pins[0]).toHaveStyle({ left: '25%', top: '75%' });
+ // A region pins its number at the top-left corner and draws the area.
+ expect(pins[1]).toHaveStyle({ left: '50%', top: '20%' });
+ const region = within(overlay).getByTestId('image-comment-region');
+ expect(parseFloat(region.style.width)).toBeCloseTo(30);
+ expect(parseFloat(region.style.height)).toBeCloseTo(60);
+ expect(within(overlay).queryByTestId('image-comment-draft')).not.toBeInTheDocument();
+ });
+
+ // Regression: text typed in the comment card was dropped by Done / Add to chat.
+ it('keeps a typed but not yet added comment on Done', () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ const layer = within(overlay).getByTestId('image-comment-layer');
+ fireEvent.pointerDown(layer, { button: 0, clientX: 50, clientY: 50, pointerId: 1 });
+ fireEvent.pointerUp(layer, { clientX: 50, clientY: 50, pointerId: 1 });
+ fireEvent.change(within(overlay).getByRole('textbox', { name: 'imageViewer.comment.add' }), {
+ target: { value: 'not added yet' },
+ });
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.done' }));
+
+ // Back on the main toolbar with the comment pending.
+ const toolbar = screen.getByRole('toolbar', { name: 'imageViewer.editTools' });
+ expect(within(toolbar).getByTestId('image-markup-send')).toBeEnabled();
+ });
+
+ it('sends a typed but not yet added comment with Add to chat', async () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ const layer = within(overlay).getByTestId('image-comment-layer');
+ fireEvent.pointerDown(layer, { button: 0, clientX: 50, clientY: 50, pointerId: 1 });
+ fireEvent.pointerUp(layer, { clientX: 50, clientY: 50, pointerId: 1 });
+ fireEvent.change(within(overlay).getByRole('textbox', { name: 'imageViewer.comment.add' }), {
+ target: { value: 'not added yet' },
+ });
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() => expect(exporter.renderImageToBlob).toHaveBeenCalled());
+ expect(
+ exporter.renderImageToBlob.mock.calls[0][1].comments.map((c: { text: string }) => c.text),
+ ).toEqual(['not added yet']);
+ // Sent, so nothing is left pending.
+ expect(
+ await screen.findByRole('toolbar', { name: 'imageViewer.editTools' }),
+ ).toBeInTheDocument();
+ expect(screen.queryByTestId('image-markup-send')).not.toBeInTheDocument();
+ });
+
+ it('cancels a draft with Escape without leaving the mode', () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ const layer = within(overlay).getByTestId('image-comment-layer');
+ fireEvent.pointerDown(layer, { button: 0, clientX: 10, clientY: 10, pointerId: 1 });
+ fireEvent.pointerUp(layer, { clientX: 10, clientY: 10, pointerId: 1 });
+
+ const input = within(overlay).getByRole('textbox', { name: 'imageViewer.comment.add' });
+ fireEvent.keyDown(input, { key: 'Escape' });
+
+ expect(within(overlay).queryByTestId('image-comment-draft')).not.toBeInTheDocument();
+ expect(screen.getByTestId('image-comment-panel')).toBeInTheDocument();
+ });
+
+ it('removes a comment from the list', () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ addComment(overlay, 'Nice sky', { x: 100, y: 50 });
+
+ const panel = screen.getByTestId('image-comment-panel');
+ fireEvent.click(within(panel).getByRole('button', { name: 'imageViewer.comment.delete' }));
+
+ expect(within(panel).queryByText('Nice sky')).not.toBeInTheDocument();
+ expect(within(panel).getByText('imageViewer.comment.empty')).toBeInTheDocument();
+ });
+
+ it('starts with the list collapsed in a narrow viewer and toggles it from the bar', async () => {
+ renderTools({ compact: true });
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.tool.comment' }));
+ expect(screen.queryByTestId('image-comment-panel')).not.toBeInTheDocument();
+
+ const toggle = screen.getByRole('button', { name: 'imageViewer.comment.title' });
+ expect(toggle).toHaveAttribute('aria-expanded', 'false');
+ fireEvent.click(toggle);
+ expect(await screen.findByTestId('image-comment-panel')).toBeInTheDocument();
+ });
+
+ it('keeps comments in memory only: a new viewer starts empty', () => {
+ const first = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ addComment(first.overlay, 'Nice sky', { x: 100, y: 50 });
+ first.unmount();
+ document.body.innerHTML = '';
+
+ renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ expect(screen.getByText('imageViewer.comment.empty')).toBeInTheDocument();
+ });
+ });
+
+ describe('add to chat', () => {
+ it('puts the marked-up image and numbered comments into the open chat input', async () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ expect(screen.getByTestId('image-markup-send')).toBeDisabled();
+ drawBox(overlay);
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.done' }));
+
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ // The drawing stays visible while commenting.
+ expect(within(overlay).getByTestId('image-markup-preview')).toBeInTheDocument();
+ addComment(overlay, 'Make this brighter', { x: 20, y: 20 });
+ addComment(overlay, 'Remove this', { x: 100, y: 20 }, { x: 160, y: 80 });
+
+ const send = screen.getByTestId('image-markup-send');
+ expect(send).toHaveTextContent('imageViewer.markup.addToChat');
+ await act(async () => {
+ fireEvent.click(send);
+ });
+
+ await waitFor(() => expect(fileStore.uploadChatFiles).toHaveBeenCalled());
+ // One image carries both the drawing and the numbered comment markers.
+ const [, options] = exporter.renderImageToBlob.mock.calls[0];
+ expect(options.shapes).toEqual([
+ expect.objectContaining({
+ rect: {
+ height: expect.closeTo(0.5),
+ width: expect.closeTo(0.5),
+ x: expect.closeTo(0.1),
+ y: expect.closeTo(0.1),
+ },
+ type: 'rect',
+ }),
+ ]);
+ expect(options.comments.map((c: { text: string }) => c.text)).toEqual([
+ 'Make this brighter',
+ 'Remove this',
+ ]);
+
+ const [[file], agentId] = fileStore.uploadChatFiles.mock.calls[0];
+ expect(file.name).toBe('sunset-annotated.png');
+ expect(agentId).toBe('agt_current');
+ // Nothing is saved to the library.
+ expect(fileStore.uploadWithProgress).not.toHaveBeenCalled();
+
+ const draft = useComposerDraftBus.getState().draft!;
+ expect(draft.append).toBe(true);
+ // Header plus one numbered line per comment (wording covered in markup.test.ts).
+ expect(draft.text.split('\n')).toEqual([
+ 'imageViewer.markup.message.headerWithDrawing',
+ 'imageViewer.markup.message.item',
+ 'imageViewer.markup.message.item',
+ ]);
+ expect(navigate).not.toHaveBeenCalled();
+ expect(toast.success).toHaveBeenCalledWith('imageViewer.markup.added');
+
+ // Sent marks are cleared, back to the main toolbar.
+ expect(
+ await screen.findByRole('toolbar', { name: 'imageViewer.editTools' }),
+ ).toBeInTheDocument();
+ expect(within(overlay).queryByTestId('image-markup-preview')).not.toBeInTheDocument();
+ });
+
+ it('offers sending from the main toolbar once something is marked', async () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+ fireEvent.keyDown(window, { key: 'Escape' });
+
+ const toolbar = screen.getByRole('toolbar', { name: 'imageViewer.editTools' });
+ expect(within(toolbar).getByTestId('image-markup-send')).toBeEnabled();
+
+ fireEvent.click(within(toolbar).getByRole('button', { name: 'imageViewer.markup.discard' }));
+ expect(screen.queryByTestId('image-markup-send')).not.toBeInTheDocument();
+ });
+
+ it('starts a chat with the inbox agent when no conversation is open', async () => {
+ useComposerDraftBus.setState({ attached: false, draft: null });
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+ addComment(overlay, 'What is this?', { x: 100, y: 50 });
+
+ const send = screen.getByTestId('image-markup-send');
+ expect(send).toHaveTextContent('imageViewer.markup.askInNewChat');
+ await act(async () => {
+ fireEvent.click(send);
+ });
+
+ await waitFor(() => expect(navigate).toHaveBeenCalledWith('/agent/agt_inbox'));
+ expect(fileStore.uploadChatFiles.mock.calls[0][1]).toBe('agt_inbox');
+ // Queued for the composer that mounts after navigating.
+ expect(useComposerDraftBus.getState().draft?.text).toContain(
+ 'imageViewer.markup.message.item',
+ );
+ });
+
+ it('undoes strokes and exits with Escape', () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ expect(screen.getByTestId('image-markup-send')).toBeEnabled();
+ fireEvent.keyDown(window, { ctrlKey: true, key: 'z' });
+ expect(screen.getByTestId('image-markup-send')).toBeDisabled();
+
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(screen.getByRole('toolbar', { name: 'imageViewer.editTools' })).toBeInTheDocument();
+ expect(within(overlay).queryByTestId('image-annotate-canvas')).not.toBeInTheDocument();
+ });
+
+ // Regression: the text and success used to land before the attachment was
+ // in the input, so Send could go out with the text alone.
+ it('keeps the marks and adds no text when the attachment does not reach the input', async () => {
+ fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.chatUploadFileList = [
+ { error: 'Upload failed', file, id: 'sunset-annotated.png', status: 'error' },
+ ];
+ });
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ id: 'sunset-annotated.png',
+ type: 'removeFile',
+ });
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(screen.getByTestId('image-markup-send')).toBeEnabled();
+ });
+
+ // Regression: switching conversations during the upload sent the marks to
+ // whichever conversation was open when it finished.
+ it('does not hand the marks to another conversation opened meanwhile', async () => {
+ fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ chatState.activeTopicId = 'tpc_other';
+ fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
+ });
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ id: 'file_chat',
+ type: 'removeFile',
+ });
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ expect(screen.getByTestId('image-markup-send')).toBeEnabled();
+ });
+
+ // Regression: marks added while the handoff uploaded were cleared unsent.
+ it('keeps marks added while the image was uploading', async () => {
+ let finishUpload!: () => void;
+ fileStore.uploadChatFiles.mockImplementation(
+ ([file]: File[]) =>
+ new Promise<void>((resolve) => {
+ finishUpload = () => {
+ fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
+ resolve();
+ };
+ }),
+ );
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+ await waitFor(() => expect(fileStore.uploadChatFiles).toHaveBeenCalled());
+ // A second box while the first one is still uploading.
+ drawBox(overlay);
+ await act(async () => finishUpload());
+
+ await waitFor(() => expect(toast.success).toHaveBeenCalledWith('imageViewer.markup.added'));
+ // Back on the main toolbar with the unsent box still pending.
+ const toolbar = await screen.findByRole('toolbar', { name: 'imageViewer.editTools' });
+ expect(within(toolbar).getByTestId('image-markup-send')).toBeEnabled();
+ });
+
+ // Regression: closing the viewer mid-upload still delivered the handoff.
+ it('drops the handoff when the viewer closes during the upload', async () => {
+ let finishUpload!: () => void;
+ fileStore.uploadChatFiles.mockImplementation(
+ ([file]: File[]) =>
+ new Promise<void>((resolve) => {
+ finishUpload = () => {
+ fileStore.chatUploadFileList = [{ file, id: 'file_chat', status: 'success' }];
+ resolve();
+ };
+ }),
+ );
+ const { overlay, unmount } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+ await waitFor(() => expect(fileStore.uploadChatFiles).toHaveBeenCalled());
+
+ unmount();
+ await act(async () => finishUpload());
+
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ id: 'file_chat',
+ type: 'removeFile',
+ });
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ // Regression: an upload that failed without throwing left a pending chip
+ // that was taken for success.
+ it('treats an attachment left pending as a failed handoff', async () => {
+ fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.chatUploadFileList = [{ file, id: 'sunset-annotated.png', status: 'pending' }];
+ });
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
+ expect(fileStore.dispatchChatUploadFileList).toHaveBeenCalledWith({
+ id: 'sunset-annotated.png',
+ type: 'removeFile',
+ });
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ });
+
+ it('judges this upload, not an earlier attachment with the same name', async () => {
+ const earlier = new File(['old'], 'sunset-annotated.png', { type: 'image/png' });
+ fileStore.chatUploadFileList = [{ file: earlier, id: 'file_earlier', status: 'success' }];
+ fileStore.uploadChatFiles.mockImplementation(async ([file]: File[]) => {
+ fileStore.chatUploadFileList = [
+ ...fileStore.chatUploadFileList,
+ { error: 'Upload failed', file, id: 'sunset-annotated.png', status: 'error' },
+ ];
+ });
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('imageViewer.markup.failed'));
+ expect(useComposerDraftBus.getState().draft).toBeNull();
+ });
+
+ it('reports when the storage does not allow reading pixels', async () => {
+ const { ImagePixelsUnavailableError } = await import('./exportImage');
+ exporter.loadStageImage.mockRejectedValue(new ImagePixelsUnavailableError());
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.annotate'));
+ drawBox(overlay);
+
+ await act(async () => {
+ fireEvent.click(screen.getByTestId('image-markup-send'));
+ });
+
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith('imageViewer.pixelsUnavailable'),
+ );
+ expect(fileStore.uploadChatFiles).not.toHaveBeenCalled();
+ // Stay in the mode so the drawing is not lost.
+ expect(within(overlay).getByTestId('image-annotate-canvas')).toBeInTheDocument();
+ });
+ });
+
+ it('disables every edit for members who cannot create content', () => {
+ permission.allowed = false;
+ permission.reason = 'No permission to create content';
+ renderTools();
+
+ const toolbar = screen.getByRole('toolbar', { name: 'imageViewer.editTools' });
+ for (const button of within(toolbar).getAllByRole('button')) {
+ expect(button).toBeDisabled();
+ expect(button).toHaveAttribute('title', 'No permission to create content');
+ }
+ });
+
+ describe('narrow viewer', () => {
+ // Regression: in the chat preview the bar wrapped onto a second line.
+ it('shows icon-only buttons with their names as labels', () => {
+ renderTools({ compact: true });
+
+ const toolbar = screen.getByRole('toolbar', { name: 'imageViewer.editTools' });
+ expect(
+ within(toolbar).getByRole('button', { name: 'imageViewer.tool.resize' }),
+ ).toBeInTheDocument();
+ expect(within(toolbar).queryByText('imageViewer.tool.resize')).toBeNull();
+ expect(within(toolbar).getAllByRole('button')).toHaveLength(5);
+ });
+
+ // Regression: the comment list covered the image in the chat preview.
+ it('opens the comment list as a sheet that reserves room below the image', () => {
+ const setReserve = vi.fn();
+ renderTools({ compact: true, setReserve });
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.tool.comment' }));
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.comment.title' }));
+
+ expect(screen.getByTestId('image-comment-panel')).toHaveAttribute('data-placement', 'bottom');
+ expect(setReserve).toHaveBeenLastCalledWith({ bottom: expect.any(Number) });
+ });
+ });
+
+ it('opens the comment list beside a wide image and reserves that room', () => {
+ const setReserve = vi.fn();
+ renderTools({ setReserve });
+ fireEvent.click(screen.getByText('imageViewer.tool.comment'));
+
+ expect(screen.getByTestId('image-comment-panel')).toHaveAttribute('data-placement', 'side');
+ expect(setReserve).toHaveBeenLastCalledWith({ right: expect.any(Number) });
+
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(setReserve).toHaveBeenLastCalledWith({});
+ });
+
+ describe('shortcuts', () => {
+ // Regression: a window-level Enter from a control elsewhere on the page
+ // (e.g. the chat beside a portal preview) triggered the tool's action.
+ it('ignores keys from outside the viewer and Enter on a focused control', () => {
+ renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.resize'));
+
+ const outside = document.createElement('button');
+ document.body.append(outside);
+ fireEvent.keyDown(outside, { key: 'Enter' });
+ fireEvent.keyDown(outside, { key: 'Escape' });
+ fireEvent.keyDown(screen.getByRole('button', { name: 'imageViewer.cancel' }), {
+ key: 'Enter',
+ });
+
+ expect(fileStore.uploadWithProgress).not.toHaveBeenCalled();
+ expect(screen.getByLabelText('imageViewer.resize.width')).toBeInTheDocument();
+ });
+ });
+
+ describe('resize', () => {
+ it('crops to a preset ratio, scales and saves a new file', async () => {
+ const { overlay } = renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.resize'));
+
+ const width = screen.getByLabelText('imageViewer.resize.width');
+ const height = screen.getByLabelText('imageViewer.resize.height');
+ expect(width).toHaveValue(2000);
+ expect(height).toHaveValue(1000);
+
+ // Ratio is locked by default: editing the width drives the height.
+ fireEvent.change(width, { target: { value: '1000' } });
+ await waitFor(() => expect(height).toHaveValue(500));
+
+ const box = within(overlay).getByTestId('image-crop-box');
+ expect(box).toHaveStyle({ height: '100%', left: '0%', top: '0%', width: '100%' });
+
+ // Drag the bottom-right handle inwards by a quarter of the box.
+ const handle = box.querySelector('[data-handle="se"]') as HTMLElement;
+ handle.setPointerCapture = vi.fn();
+ fireEvent.pointerDown(handle, { button: 0, clientX: 200, clientY: 100, pointerId: 1 });
+ fireEvent.pointerMove(handle, { clientX: 150, clientY: 75, pointerId: 1 });
+ fireEvent.pointerUp(handle, { pointerId: 1 });
+ expect(box).toHaveStyle({ height: '75%', width: '75%' });
+ // A new crop resets the output to the crop's pixel size.
+ expect(width).toHaveValue(1500);
+ expect(height).toHaveValue(750);
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.saveAsNew' }));
+ });
+
+ await waitFor(() => expect(fileStore.uploadWithProgress).toHaveBeenCalled());
+ expect(exporter.renderImageToBlob.mock.calls[0][1]).toEqual({
+ crop: { height: 0.75, width: 0.75, x: 0, y: 0 },
+ output: { height: 750, width: 1500 },
+ });
+ const upload = fileStore.uploadWithProgress.mock.calls[0][0];
+ expect(upload.file.name).toBe('sunset-resized.png');
+ expect(upload.fileMetadata.derivedFrom.operation).toBe('resize');
+ });
+
+ it('lets a size field be emptied while typing', () => {
+ renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.resize'));
+ const width = screen.getByLabelText('imageViewer.resize.width');
+
+ fireEvent.change(width, { target: { value: '' } });
+ expect(width).toHaveValue(null);
+ fireEvent.change(width, { target: { value: '800' } });
+ expect(screen.getByLabelText('imageViewer.resize.height')).toHaveValue(400);
+
+ fireEvent.blur(width);
+ expect(width).toHaveValue(800);
+ });
+
+ it('cancels with Escape even while a size field has focus', () => {
+ renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.resize'));
+ const width = screen.getByLabelText('imageViewer.resize.width');
+ width.focus();
+ fireEvent.keyDown(width, { key: 'Escape' });
+
+ expect(screen.getByRole('toolbar', { name: 'imageViewer.editTools' })).toBeInTheDocument();
+ expect(fileStore.uploadWithProgress).not.toHaveBeenCalled();
+ });
+
+ it('cancels back to the toolbar without saving', () => {
+ renderTools();
+ fireEvent.click(screen.getByText('imageViewer.tool.resize'));
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.cancel' }));
+
+ expect(screen.getByRole('toolbar', { name: 'imageViewer.editTools' })).toBeInTheDocument();
+ expect(fileStore.uploadWithProgress).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/index.tsx b/src/features/FileViewer/Renderer/Image/Tools/index.tsx
new file mode 100644
index 00000000000..7a3fbed5ac4
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/index.tsx
@@ -0,0 +1,153 @@
+'use client';
+
+import { ActionIcon, Badge } from '@lobehub/ui/base-ui';
+import {
+ CropIcon,
+ EraserIcon,
+ MessageSquarePlusIcon,
+ PencilLineIcon,
+ WandSparklesIcon,
+ XIcon,
+} from 'lucide-react';
+import { lazy, Suspense, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePermission } from '@/hooks/usePermission';
+
+import { useImageStage } from '../context';
+import AnnotateMode from './Annotate';
+import BarButton from './BarButton';
+import CommentMode from './Comment';
+import { EMPTY_MARKUP, type ImageMarkup, isMarkupEmpty } from './markup';
+import MarkupPreview from './MarkupPreview';
+import ResizeMode from './Resize';
+import SendToChatButton from './SendToChatButton';
+import { toolStyles as styles } from './styles';
+
+// AI editing pulls in the model and generation services; load it only when used.
+const AIEditMode = lazy(() => import('./AIEdit'));
+
+type ToolMode = 'annotate' | 'comment' | 'erase' | 'removeBackground' | 'resize';
+
+/**
+ * Editing tools for a persisted image file: the floating bottom toolbar and
+ * the annotate / comment / remove background / erase / resize workflows it
+ * opens. Mounted by hosts that show a real library file; each workflow
+ * renders its own bar while active.
+ *
+ * Annotations and comments are not saved with the file. They are marks for a
+ * follow-up chat message, kept in the viewer's memory per version (closing the
+ * viewer drops them) until the user adds them to the chat input.
+ */
+const ImageEditTools = () => {
+ const { t } = useTranslation('file');
+ const { fitToScreen, markup, setMarkup } = useImageStage();
+ const [mode, setMode] = useState<ToolMode | null>(null);
+ // Every workflow ends in a new upload (file or chat attachment) or an image
+ // generation, so members who cannot create content cannot start one.
+ const { allowed: canCreate, reason } = usePermission('create_content');
+ const { comments } = markup;
+
+ const enter = (next: ToolMode) => {
+ // Edits start from the whole image on screen, so pointer mapping is predictable.
+ fitToScreen();
+ setMode(next);
+ };
+ const exit = () => setMode(null);
+ // Marks added while the handoff was uploading were not sent; keep them.
+ const clearAfterSend = (sent: ImageMarkup) => {
+ setMarkup((current) => (current === sent ? EMPTY_MARKUP : current));
+ setMode(null);
+ };
+
+ const markupProps = { markup, onChange: setMarkup, onExit: exit, onSent: clearAfterSend };
+ if (mode === 'annotate') return <AnnotateMode {...markupProps} />;
+ if (mode === 'comment') return <CommentMode {...markupProps} />;
+ if (mode === 'removeBackground' || mode === 'erase')
+ return (
+ <Suspense fallback={null}>
+ <AIEditMode key={mode} operation={mode} onExit={exit} />
+ </Suspense>
+ );
+ if (mode === 'resize') return <ResizeMode onExit={exit} />;
+
+ const hasMarkup = !isMarkupEmpty(markup);
+
+ return (
+ <div className={styles.dock}>
+ <MarkupPreview comments={markup.comments} shapes={markup.shapes} />
+ <div
+ aria-label={t('imageViewer.editTools')}
+ className={styles.bar}
+ data-testid={'image-edit-toolbar'}
+ role={'toolbar'}
+ >
+ <BarButton
+ disabled={!canCreate}
+ icon={PencilLineIcon}
+ label={t('imageViewer.tool.annotate')}
+ title={reason}
+ type={'text'}
+ onClick={() => enter('annotate')}
+ />
+ <BarButton
+ disabled={!canCreate}
+ icon={MessageSquarePlusIcon}
+ label={t('imageViewer.tool.comment')}
+ title={reason}
+ type={'text'}
+ extra={
+ comments.length > 0 && (
+ <Badge
+ aria-label={t('imageViewer.comment.count', { count: comments.length })}
+ count={comments.length}
+ size={'small'}
+ style={{ marginInlineStart: 4 }}
+ />
+ )
+ }
+ onClick={() => enter('comment')}
+ />
+ <BarButton
+ disabled={!canCreate}
+ icon={WandSparklesIcon}
+ label={t('imageViewer.tool.removeBackground')}
+ title={reason}
+ type={'text'}
+ onClick={() => enter('removeBackground')}
+ />
+ <BarButton
+ disabled={!canCreate}
+ icon={EraserIcon}
+ label={t('imageViewer.tool.erase')}
+ title={reason}
+ type={'text'}
+ onClick={() => enter('erase')}
+ />
+ <BarButton
+ disabled={!canCreate}
+ icon={CropIcon}
+ label={t('imageViewer.tool.resize')}
+ title={reason}
+ type={'text'}
+ onClick={() => enter('resize')}
+ />
+ {hasMarkup && (
+ <>
+ <span className={styles.divider} />
+ <ActionIcon
+ aria-label={t('imageViewer.markup.discard')}
+ icon={XIcon}
+ size={'small'}
+ title={t('imageViewer.markup.discard')}
+ onClick={() => setMarkup(EMPTY_MARKUP)}
+ />
+ <SendToChatButton markup={markup} onSent={clearAfterSend} />
+ </>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default ImageEditTools;
diff --git a/src/features/FileViewer/Renderer/Image/Tools/markup.test.ts b/src/features/FileViewer/Renderer/Image/Tools/markup.test.ts
new file mode 100644
index 00000000000..eccfa4e3f02
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/markup.test.ts
@@ -0,0 +1,78 @@
+import type { TFunction } from 'i18next';
+import { describe, expect, it } from 'vitest';
+
+import { buildMarkupMessage, describeAnchor, describeArea, type ImageMarkup } from './markup';
+
+// Echo the key and its values so the assertions read the full sentence shape.
+const t = ((key: string, options?: Record<string, unknown>) =>
+ options ? `${key} ${JSON.stringify(options)}` : key) as unknown as TFunction<'file'>;
+
+const brush = { color: '#f00', points: [{ x: 0, y: 0 }], size: 0.01, type: 'brush' as const };
+
+describe('describeArea', () => {
+ it.each([
+ [{ x: 0.1, y: 0.1 }, 'topLeft'],
+ [{ x: 0.5, y: 0.1 }, 'top'],
+ [{ x: 0.9, y: 0.1 }, 'topRight'],
+ [{ x: 0.1, y: 0.5 }, 'left'],
+ [{ x: 0.5, y: 0.5 }, 'center'],
+ [{ x: 0.9, y: 0.5 }, 'right'],
+ [{ x: 0.1, y: 0.9 }, 'bottomLeft'],
+ [{ x: 0.5, y: 0.9 }, 'bottom'],
+ [{ x: 0.9, y: 0.9 }, 'bottomRight'],
+ ])('%o is %s', (point, area) => {
+ expect(describeArea(point)).toBe(area);
+ });
+});
+
+describe('describeAnchor', () => {
+ it('gives a point its area and rounded percentages', () => {
+ expect(describeAnchor({ point: { x: 0.123, y: 0.876 }, type: 'point' }, t)).toBe(
+ 'imageViewer.markup.location.point {"area":"imageViewer.markup.area.bottomLeft","x":12,"y":88}',
+ );
+ });
+
+ it('gives a region its span, located by its center', () => {
+ expect(
+ describeAnchor({ rect: { height: 0.3, width: 0.3, x: 0.6, y: 0.05 }, type: 'region' }, t),
+ ).toBe(
+ 'imageViewer.markup.location.region {"area":"imageViewer.markup.area.topRight","x1":60,"x2":90,"y1":5,"y2":35}',
+ );
+ });
+});
+
+describe('buildMarkupMessage', () => {
+ const comments: ImageMarkup['comments'] = [
+ { anchor: { point: { x: 0.5, y: 0.5 }, type: 'point' }, id: 'a', text: ' Too dark ' },
+ {
+ anchor: { rect: { height: 0.1, width: 0.1, x: 0, y: 0 }, type: 'region' },
+ id: 'b',
+ text: 'Remove',
+ },
+ ];
+ const plain = ((key: string) => key) as unknown as TFunction<'file'>;
+
+ it('numbers comments in the order they were added', () => {
+ const lines = buildMarkupMessage({ comments, shapes: [] }, { name: 'a.png', t }).split('\n');
+
+ expect(lines[0]).toBe('imageViewer.markup.message.header {"name":"a.png"}');
+ expect(lines).toHaveLength(3);
+ expect(lines[1]).toMatch(/^imageViewer\.markup\.message\.item \{"index":1,/);
+ expect(lines[1]).toContain('"text":"Too dark"');
+ expect(lines[1]).toContain('imageViewer.markup.location.point');
+ expect(lines[2]).toMatch(/^imageViewer\.markup\.message\.item \{"index":2,/);
+ expect(lines[2]).toContain('"text":"Remove"');
+ expect(lines[2]).toContain('imageViewer.markup.location.region');
+ });
+
+ it('mentions the drawing when there is one', () => {
+ const text = buildMarkupMessage({ comments, shapes: [brush] }, { t: plain });
+ expect(text.split('\n')[0]).toBe('imageViewer.markup.message.headerWithDrawing');
+ });
+
+ it('is a single line for a drawing without comments', () => {
+ expect(buildMarkupMessage({ comments: [], shapes: [brush] }, { name: 'a.png', t })).toBe(
+ 'imageViewer.markup.message.drawingOnly {"name":"a.png"}',
+ );
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/markup.ts b/src/features/FileViewer/Renderer/Image/Tools/markup.ts
new file mode 100644
index 00000000000..8b7c5b44997
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/markup.ts
@@ -0,0 +1,177 @@
+import type { TFunction } from 'i18next';
+
+import type { NormalizedRect, Point } from '../geometry';
+import type { AnnotationShape } from './Annotate/shapes';
+
+export const MARKUP_COMMENT_MAX_LENGTH = 1000;
+
+/** A comment pinned to a point, or to a region dragged out on the image. */
+export type MarkupAnchor =
+ { point: Point; type: 'point' } | { rect: NormalizedRect; type: 'region' };
+
+export interface MarkupComment {
+ anchor: MarkupAnchor;
+ id: string;
+ text: string;
+}
+
+/**
+ * Marks the user puts on the image before asking about it in chat. They only
+ * live in the viewer's memory: closing the viewer drops them.
+ */
+export interface ImageMarkup {
+ comments: MarkupComment[];
+ shapes: AnnotationShape[];
+}
+
+export const EMPTY_MARKUP: ImageMarkup = { comments: [], shapes: [] };
+
+export const isMarkupEmpty = (markup: ImageMarkup) =>
+ markup.comments.length === 0 && markup.shapes.length === 0;
+
+/** Where a pin's number badge sits: the point itself, or a region's top-left corner. */
+export const anchorOrigin = (anchor: MarkupAnchor): Point =>
+ anchor.type === 'point' ? anchor.point : { x: anchor.rect.x, y: anchor.rect.y };
+
+export const anchorCenter = (anchor: MarkupAnchor): Point =>
+ anchor.type === 'point'
+ ? anchor.point
+ : { x: anchor.rect.x + anchor.rect.width / 2, y: anchor.rect.y + anchor.rect.height / 2 };
+
+export type MarkupArea =
+ | 'bottom'
+ | 'bottomLeft'
+ | 'bottomRight'
+ | 'center'
+ | 'left'
+ | 'right'
+ | 'top'
+ | 'topLeft'
+ | 'topRight';
+
+/** Coarse 3×3 area of the image a point falls in, for a readable location. */
+export const describeArea = ({ x, y }: Point): MarkupArea => {
+ const col = x < 1 / 3 ? 'left' : x > 2 / 3 ? 'right' : 'center';
+ const row = y < 1 / 3 ? 'top' : y > 2 / 3 ? 'bottom' : 'middle';
+ if (row === 'middle') return col;
+ if (col === 'center') return row;
+ return `${row}${col === 'left' ? 'Left' : 'Right'}` as MarkupArea;
+};
+
+const percent = (value: number) => Math.round(value * 100);
+
+type Translate = TFunction<'file'>;
+
+/** `top left (x 12%, y 20%)` or `region top left (x 10–40%, y 5–30%)`. */
+export const describeAnchor = (anchor: MarkupAnchor, t: Translate) => {
+ const area = t(`imageViewer.markup.area.${describeArea(anchorCenter(anchor))}`);
+ if (anchor.type === 'point')
+ return t('imageViewer.markup.location.point', {
+ area,
+ x: percent(anchor.point.x),
+ y: percent(anchor.point.y),
+ });
+
+ const { height, width, x, y } = anchor.rect;
+ return t('imageViewer.markup.location.region', {
+ area,
+ x1: percent(x),
+ x2: percent(x + width),
+ y1: percent(y),
+ y2: percent(y + height),
+ });
+};
+
+/**
+ * The text that goes into the chat input next to the marked-up image: one
+ * numbered line per comment, matching the numbers drawn on the image.
+ */
+export const buildMarkupMessage = (
+ markup: ImageMarkup,
+ { name, t }: { name?: string; t: Translate },
+) => {
+ const hasDrawing = markup.shapes.length > 0;
+ const header = t(
+ markup.comments.length === 0
+ ? 'imageViewer.markup.message.drawingOnly'
+ : hasDrawing
+ ? 'imageViewer.markup.message.headerWithDrawing'
+ : 'imageViewer.markup.message.header',
+ { name: name || 'image' },
+ );
+ const lines = markup.comments.map((comment, index) =>
+ t('imageViewer.markup.message.item', {
+ index: index + 1,
+ location: describeAnchor(comment.anchor, t),
+ text: comment.text.trim(),
+ }),
+ );
+ return [header, ...lines].join('\n');
+};
+
+type MarkerContext = Pick<
+ CanvasRenderingContext2D,
+ | 'arc'
+ | 'beginPath'
+ | 'fill'
+ | 'fillStyle'
+ | 'fillText'
+ | 'font'
+ | 'lineWidth'
+ | 'setLineDash'
+ | 'stroke'
+ | 'strokeRect'
+ | 'strokeStyle'
+ | 'textAlign'
+ | 'textBaseline'
+>;
+
+export const MARKER_COLOR = '#0a84ff';
+
+/**
+ * Draw numbered comment markers in pixel space of a `width × height` canvas,
+ * so the exported image carries the same numbers as the message text.
+ */
+export const drawCommentMarkers = (
+ ctx: MarkerContext,
+ comments: MarkupComment[],
+ width: number,
+ height: number,
+) => {
+ const unit = Math.min(width, height);
+ const radius = Math.max(10, unit * 0.022);
+
+ comments.forEach((comment, index) => {
+ const { anchor } = comment;
+ if (anchor.type === 'region') {
+ ctx.strokeStyle = MARKER_COLOR;
+ ctx.lineWidth = Math.max(2, unit * 0.004);
+ ctx.setLineDash([radius * 0.6, radius * 0.4]);
+ ctx.strokeRect(
+ anchor.rect.x * width,
+ anchor.rect.y * height,
+ anchor.rect.width * width,
+ anchor.rect.height * height,
+ );
+ ctx.setLineDash([]);
+ }
+
+ const origin = anchorOrigin(anchor);
+ const cx = Math.min(Math.max(origin.x * width, radius), width - radius);
+ const cy = Math.min(Math.max(origin.y * height, radius), height - radius);
+
+ ctx.beginPath();
+ ctx.arc(cx, cy, radius, 0, Math.PI * 2);
+ ctx.fillStyle = MARKER_COLOR;
+ ctx.fill();
+ ctx.lineWidth = Math.max(2, radius * 0.18);
+ ctx.strokeStyle = '#ffffff';
+ ctx.stroke();
+
+ ctx.fillStyle = '#ffffff';
+ ctx.font = `600 ${Math.round(radius * 1.1)}px sans-serif`;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(String(index + 1), cx, cy);
+ });
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/saveDerivedFile.test.ts b/src/features/FileViewer/Renderer/Image/Tools/saveDerivedFile.test.ts
new file mode 100644
index 00000000000..b5173142756
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/saveDerivedFile.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { saveDerivedFile, type SaveDerivedFileDeps } from './saveDerivedFile';
+
+const createDeps = (overrides: Partial<SaveDerivedFileDeps> = {}) =>
+ ({
+ addToKnowledgeBase: vi.fn().mockResolvedValue(undefined),
+ getFile: vi.fn().mockResolvedValue({ knowledgeBaseIds: [], parentId: null }),
+ uploadFile: vi.fn().mockResolvedValue({ id: 'file_new', url: 'files/new.png' }),
+ ...overrides,
+ }) as SaveDerivedFileDeps & Record<keyof SaveDerivedFileDeps, ReturnType<typeof vi.fn>>;
+
+const params = {
+ file: new File(['x'], 'sunset-resized.png', { type: 'image/png' }),
+ metadata: { derivedFrom: { fileId: 'file_src', operation: 'resize' } },
+ sourceId: 'file_src',
+};
+
+describe('saveDerivedFile', () => {
+ it('files the edit into every library the original belongs to', async () => {
+ const deps = createDeps({
+ getFile: vi.fn().mockResolvedValue({ knowledgeBaseIds: ['kb_1', 'kb_2'], parentId: null }),
+ });
+
+ const result = await saveDerivedFile(deps, params);
+
+ expect(result).toEqual({ id: 'file_new', libraryFailed: false, url: 'files/new.png' });
+ expect(deps.getFile).toHaveBeenCalledWith('file_src');
+ expect(deps.addToKnowledgeBase).toHaveBeenCalledWith('kb_1', ['file_new']);
+ expect(deps.addToKnowledgeBase).toHaveBeenCalledWith('kb_2', ['file_new']);
+ });
+
+ it('uses the folder reported by the server over the client hint', async () => {
+ const deps = createDeps({
+ getFile: vi.fn().mockResolvedValue({ knowledgeBaseIds: [], parentId: 'docs_server' }),
+ });
+
+ await saveDerivedFile(deps, { ...params, parentId: 'docs_client' });
+
+ expect(deps.uploadFile).toHaveBeenCalledWith({
+ file: params.file,
+ metadata: params.metadata,
+ parentId: 'docs_server',
+ });
+ expect(deps.addToKnowledgeBase).not.toHaveBeenCalled();
+ });
+
+ // Regression: a top-level upload defaults to private, hiding edits of a
+ // public workspace image from collaborators who can see the original.
+ it('keeps the visibility of the original', async () => {
+ const deps = createDeps({
+ getFile: vi
+ .fn()
+ .mockResolvedValue({ knowledgeBaseIds: [], parentId: null, visibility: 'public' }),
+ });
+
+ await saveDerivedFile(deps, params);
+
+ expect(deps.uploadFile).toHaveBeenCalledWith(expect.objectContaining({ visibility: 'public' }));
+ });
+
+ it('saves at the top level when the server says the original moved there', async () => {
+ const deps = createDeps({
+ getFile: vi.fn().mockResolvedValue({ knowledgeBaseIds: [], parentId: null }),
+ });
+
+ await saveDerivedFile(deps, { ...params, parentId: 'docs_stale' });
+
+ expect(deps.uploadFile).toHaveBeenCalledWith(expect.objectContaining({ parentId: undefined }));
+ });
+
+ it('still saves beside the client-known folder when the lookup fails', async () => {
+ const deps = createDeps({ getFile: vi.fn().mockRejectedValue(new Error('offline')) });
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+
+ const result = await saveDerivedFile(deps, { ...params, parentId: 'docs_client' });
+
+ expect(result?.id).toBe('file_new');
+ expect(deps.uploadFile).toHaveBeenCalledWith(
+ expect.objectContaining({ parentId: 'docs_client' }),
+ );
+ });
+
+ // Regression: the failed link used to be swallowed and reported as full success.
+ it('keeps the saved file and reports it when adding it to a library fails', async () => {
+ const deps = createDeps({
+ addToKnowledgeBase: vi.fn().mockRejectedValue(new Error('denied')),
+ getFile: vi.fn().mockResolvedValue({ knowledgeBaseIds: ['kb_1'], parentId: null }),
+ });
+ vi.spyOn(console, 'error').mockImplementation(() => undefined);
+
+ await expect(saveDerivedFile(deps, params)).resolves.toEqual({
+ id: 'file_new',
+ libraryFailed: true,
+ url: 'files/new.png',
+ });
+ });
+
+ it('adds nothing to libraries when the upload does not complete', async () => {
+ const deps = createDeps({
+ getFile: vi.fn().mockResolvedValue({ knowledgeBaseIds: ['kb_1'], parentId: null }),
+ uploadFile: vi.fn().mockResolvedValue(undefined),
+ });
+
+ expect(await saveDerivedFile(deps, params)).toBeUndefined();
+ expect(deps.addToKnowledgeBase).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/Tools/saveDerivedFile.ts b/src/features/FileViewer/Renderer/Image/Tools/saveDerivedFile.ts
new file mode 100644
index 00000000000..4332942a39e
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/saveDerivedFile.ts
@@ -0,0 +1,61 @@
+import type { AIEditDeps } from './AIEdit/runAIImageEdit';
+
+export type SaveDerivedFileDeps = Pick<AIEditDeps, 'addToKnowledgeBase' | 'getFile' | 'uploadFile'>;
+
+export interface SaveDerivedFileParams {
+ file: File;
+ metadata: Record<string, unknown>;
+ /** Folder known on the client, used when the server lookup fails. */
+ parentId?: string | null;
+ sourceId: string;
+}
+
+/**
+ * Add a saved edit to the original's libraries. The file is already saved, so
+ * a failed link is reported (it only hides the file in that library) rather
+ * than thrown. Returns whether any link failed.
+ */
+export const fileIntoLibraries = async (
+ deps: Pick<SaveDerivedFileDeps, 'addToKnowledgeBase'>,
+ knowledgeBaseIds: string[] | undefined,
+ fileId: string,
+) => {
+ let failed = false;
+ for (const knowledgeBaseId of knowledgeBaseIds ?? []) {
+ await deps.addToKnowledgeBase(knowledgeBaseId, [fileId]).catch((error) => {
+ console.error('[ImageViewer] failed to add the edited image to its library', error);
+ failed = true;
+ });
+ }
+ return failed;
+};
+
+/**
+ * Upload an edited image as a new file beside its original: same folder and
+ * same libraries. The original file is only read, never written.
+ */
+export const saveDerivedFile = async (
+ deps: SaveDerivedFileDeps,
+ { file, metadata, parentId, sourceId }: SaveDerivedFileParams,
+) => {
+ // Hosts such as the image grid or a library view do not carry the original's
+ // folder and libraries on the client, so ask the server where it lives.
+ const location = await deps.getFile(sourceId).catch((error) => {
+ console.error('[ImageViewer] failed to read the original image location', error);
+ return undefined;
+ });
+
+ const result = await deps.uploadFile({
+ file,
+ metadata,
+ // A successful lookup wins even when it reports the top level (null).
+ parentId: (location ? location.parentId : parentId) ?? undefined,
+ // Collaborators who can see the original should see the edit too.
+ visibility: location?.visibility ?? undefined,
+ });
+ if (!result) return;
+
+ const libraryFailed = await fileIntoLibraries(deps, location?.knowledgeBaseIds, result.id);
+
+ return { ...result, libraryFailed };
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/styles.ts b/src/features/FileViewer/Renderer/Image/Tools/styles.ts
new file mode 100644
index 00000000000..93c7565737c
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/styles.ts
@@ -0,0 +1,112 @@
+import { createStaticStyles, cssVar } from 'antd-style';
+
+/** Shared chrome for the floating bottom bar and side panels of the image tools. */
+export const toolStyles = createStaticStyles(({ css }) => ({
+ bar: css`
+ pointer-events: auto;
+
+ display: flex;
+ flex-wrap: nowrap;
+ gap: 4px;
+ align-items: center;
+ justify-content: center;
+
+ max-width: 100%;
+ padding: 4px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 999px;
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowSecondary};
+ `,
+ divider: css`
+ flex-shrink: 0;
+
+ width: 1px;
+ height: 20px;
+ margin-inline: 4px;
+
+ background: ${cssVar.colorSplit};
+ `,
+ dock: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 3;
+ inset-block-end: 12px;
+ inset-inline: 12px;
+
+ display: flex;
+ justify-content: center;
+ `,
+ hint: css`
+ overflow: hidden;
+ flex-shrink: 1;
+
+ min-width: 0;
+ padding-inline: 8px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ overlayFill: css`
+ position: absolute;
+ inset: 0;
+ `,
+ panel: css`
+ position: absolute;
+ z-index: 3;
+ inset-block: 52px 68px;
+ inset-inline-end: 8px;
+
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ width: min(280px, calc(100% - 16px));
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowSecondary};
+ `,
+ /** The panel on a narrow viewer: a sheet above the bar, as wide as the viewer. */
+ sheet: css`
+ position: absolute;
+ z-index: 3;
+ inset-block-end: 60px;
+ inset-inline: 8px;
+
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+
+ max-height: 40%;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowSecondary};
+ `,
+ swatch: css`
+ cursor: pointer;
+
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: 2px solid ${cssVar.colorBorder};
+ border-radius: 50%;
+
+ &[aria-pressed='true'] {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: 1px;
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: 1px;
+ }
+ `,
+}));
diff --git a/src/features/FileViewer/Renderer/Image/Tools/useSaveDerivedImage.ts b/src/features/FileViewer/Renderer/Image/Tools/useSaveDerivedImage.ts
new file mode 100644
index 00000000000..733f5d1b42b
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/useSaveDerivedImage.ts
@@ -0,0 +1,74 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { useCallback, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { fileManagerSelectors, useFileStore } from '@/store/file';
+
+import { useImageStage } from '../context';
+import {
+ buildDerivedFileMetadata,
+ buildDerivedFileName,
+ DERIVED_FILE_SUFFIX,
+ type DerivedImageOperation,
+} from '../geometry';
+import { aiEditDeps, loadStageImage } from './AIEdit/deps';
+import { ImagePixelsUnavailableError } from './exportImage';
+import { saveDerivedFile } from './saveDerivedFile';
+
+/**
+ * Render an edit of the current image and upload it as a new file next to the
+ * original (same folder and libraries), recording lineage in metadata. The
+ * original is kept.
+ */
+export const useSaveDerivedImage = (operation: DerivedImageOperation) => {
+ const { t } = useTranslation('file');
+ const { addVersion, fileId, name, setBusy, url } = useImageStage();
+ const [saving, setSaving] = useState(false);
+ // One save at a time, even if a shortcut fires before the state re-renders.
+ const savingRef = useRef(false);
+
+ const save = useCallback(
+ async (render: (img: HTMLImageElement) => Promise<Blob>) => {
+ if (savingRef.current) return;
+ savingRef.current = true;
+ setSaving(true);
+ setBusy(true);
+ try {
+ const img = await loadStageImage(url);
+ const blob = await render(img);
+ const fileName = buildDerivedFileName(name, DERIVED_FILE_SUFFIX[operation]);
+ const { refreshFileList } = useFileStore.getState();
+ const source = fileManagerSelectors.getFileByChunkTargetId(fileId)(useFileStore.getState());
+
+ const result = await saveDerivedFile(aiEditDeps, {
+ file: new File([blob], fileName, { type: blob.type || 'image/png' }),
+ metadata: buildDerivedFileMetadata(fileId, operation),
+ parentId: source?.parentId,
+ sourceId: fileId,
+ });
+ if (!result) return;
+
+ void refreshFileList({ revalidateResources: true });
+ if (result.libraryFailed)
+ toast.warning(t('imageViewer.savedNotInLibrary', { name: fileName }));
+ else toast.success(t('imageViewer.saved', { name: fileName }));
+ addVersion({ fileId: result.id, name: fileName, operation, url: result.url });
+ return { ...result, name: fileName };
+ } catch (error) {
+ console.error('[ImageViewer] save derived image failed', error);
+ toast.error(
+ error instanceof ImagePixelsUnavailableError
+ ? t('imageViewer.pixelsUnavailable')
+ : t('imageViewer.saveFailed'),
+ );
+ } finally {
+ savingRef.current = false;
+ setSaving(false);
+ setBusy(false);
+ }
+ },
+ [addVersion, fileId, name, operation, setBusy, t, url],
+ );
+
+ return { save, saving };
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts b/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts
new file mode 100644
index 00000000000..92af422c114
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/useSendMarkupToChat.ts
@@ -0,0 +1,140 @@
+import { AGENT_CHAT_URL } from '@lobechat/const';
+import { toast } from '@lobehub/ui/base-ui';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import {
+ draftToMainComposer,
+ queueDraftForMainComposer,
+ useComposerDraftBus,
+} from '@/features/Conversation/composerDraftBus';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { useFileStore } from '@/store/file';
+
+import { useImageStage } from '../context';
+import { buildDerivedFileName } from '../geometry';
+import { loadStageImage } from './AIEdit/deps';
+import { ImagePixelsUnavailableError, renderImageToBlob } from './exportImage';
+import { buildMarkupMessage, type ImageMarkup, isMarkupEmpty } from './markup';
+
+/**
+ * Hand the marked-up image to chat: the image with its drawings and numbered
+ * comment markers becomes an attachment, and the comments become text in the
+ * chat input. Nothing is sent; the user reviews the input and sends it.
+ *
+ * Next to a conversation (the chat file preview) both land in its input. From
+ * a surface without one (the resource library), they wait for the inbox
+ * agent's input and the viewer navigates there.
+ */
+export const useSendMarkupToChat = () => {
+ const { t } = useTranslation('file');
+ const { name, setBusy, url } = useImageStage();
+ const navigate = useWorkspaceAwareNavigate();
+ const hasComposer = useComposerDraftBus((s) => s.attached);
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const [sending, setSending] = useState(false);
+ // The handoff must not land after the viewer that started it is gone.
+ const aliveRef = useRef(true);
+ useEffect(() => {
+ aliveRef.current = true;
+ return () => {
+ aliveRef.current = false;
+ };
+ }, []);
+
+ const send = useCallback(
+ async (markup: ImageMarkup): Promise<boolean> => {
+ if (isMarkupEmpty(markup)) return false;
+ const attached = useComposerDraftBus.getState().attached;
+ const { activeAgentId, activeTopicId } = useChatStore.getState();
+ const agentId = attached ? activeAgentId : inboxAgentId;
+ if (!agentId) {
+ toast.error(t('imageViewer.markup.noConversation'));
+ return false;
+ }
+
+ setSending(true);
+ // Keeps the viewer's Close disabled while the image is on its way.
+ setBusy(true);
+ try {
+ const img = await loadStageImage(url);
+ const blob = await renderImageToBlob(img, {
+ comments: markup.comments,
+ shapes: markup.shapes,
+ });
+ const file = new File([blob], buildDerivedFileName(name, 'annotated'), {
+ type: blob.type || 'image/png',
+ });
+ const text = buildMarkupMessage(markup, { name, t });
+
+ // Wait for the attachment to be in the input (compressed, read and
+ // uploaded) before adding the text and dropping the marks, so Send can
+ // never go out with the text alone.
+ // Another annotation of the same image may already be in the input
+ // under the same name; only the item this upload adds counts.
+ // The export and upload take a while; if the user moved to another
+ // conversation meanwhile, the marks must not land there.
+ const isStillTarget = () => {
+ const chat = useChatStore.getState();
+ return (
+ aliveRef.current &&
+ useComposerDraftBus.getState().attached === attached &&
+ (!attached ||
+ (chat.activeAgentId === activeAgentId && chat.activeTopicId === activeTopicId))
+ );
+ };
+ if (!isStillTarget())
+ throw new Error('The conversation changed before the image was ready');
+
+ const before = new Set(useFileStore.getState().chatUploadFileList.map((item) => item.id));
+ await useFileStore.getState().uploadChatFiles([file], agentId);
+ const staged = useFileStore
+ .getState()
+ .chatUploadFileList.find((item) => !before.has(item.id) && item.file?.name === file.name);
+ // Only a finished upload counts: a failed upload can also leave the
+ // chip pending without throwing.
+ if (!staged || staged.status !== 'success') {
+ // Keep the marks for another try instead of a broken chip in the input.
+ if (staged)
+ useFileStore
+ .getState()
+ .dispatchChatUploadFileList({ id: staged.id, type: 'removeFile' });
+ throw new Error(staged?.error ?? 'The annotated image did not reach the input');
+ }
+ if (!isStillTarget()) {
+ useFileStore.getState().dispatchChatUploadFileList({ id: staged.id, type: 'removeFile' });
+ throw new Error('The conversation changed while the image was uploading');
+ }
+
+ if (attached) {
+ if (!draftToMainComposer(text, { append: true }))
+ throw new Error('The chat input is no longer open');
+ toast.success(t('imageViewer.markup.added'));
+ } else {
+ queueDraftForMainComposer(text, { agentId });
+ navigate(AGENT_CHAT_URL(agentId));
+ }
+ return true;
+ } catch (error) {
+ // Closed meanwhile: the user discarded this handoff, nothing to report.
+ if (!aliveRef.current) return false;
+ console.error('[ImageViewer] send markup to chat failed', error);
+ toast.error(
+ error instanceof ImagePixelsUnavailableError
+ ? t('imageViewer.pixelsUnavailable')
+ : t('imageViewer.markup.failed'),
+ );
+ return false;
+ } finally {
+ setBusy(false);
+ if (aliveRef.current) setSending(false);
+ }
+ },
+ [inboxAgentId, name, navigate, setBusy, t, url],
+ );
+
+ return { hasComposer, send, sending };
+};
diff --git a/src/features/FileViewer/Renderer/Image/Tools/useToolKeys.ts b/src/features/FileViewer/Renderer/Image/Tools/useToolKeys.ts
new file mode 100644
index 00000000000..020be070588
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/Tools/useToolKeys.ts
@@ -0,0 +1,68 @@
+import { useEffect, useRef } from 'react';
+
+interface ToolKeyHandlers {
+ onEnter?: () => void;
+ onEscape?: () => void;
+ onUndo?: () => void;
+}
+
+const isTypingTarget = (target: EventTarget | null) =>
+ target instanceof HTMLElement &&
+ (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));
+
+/**
+ * Shortcuts belong to the viewer: a key pressed on another part of the page
+ * (the chat next to a portal preview) is not for the tool. With nothing
+ * focused the event targets the body, which still counts.
+ */
+const isOutsideViewer = (target: EventTarget | null) =>
+ target instanceof HTMLElement &&
+ target !== document.body &&
+ !target.closest('[data-testid="image-viewer"]');
+
+/** Enter on a focused control activates that control, not the tool's primary action. */
+const isControlTarget = (target: EventTarget | null) =>
+ target instanceof HTMLElement &&
+ !!target.closest('button, a[href], [role="button"], [role="menuitem"], [role="option"]');
+
+/**
+ * Keyboard shortcuts for an active tool mode: Esc cancels, Enter completes,
+ * ⌘/Ctrl+Z undoes. Ignored while the user is typing into a field, except Esc
+ * from a single-line input.
+ */
+export const useToolKeys = (handlers: ToolKeyHandlers) => {
+ const ref = useRef(handlers);
+ useEffect(() => {
+ ref.current = handlers;
+ });
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.defaultPrevented) return;
+ const { onEnter, onEscape, onUndo } = ref.current;
+ // Esc still cancels from a single-line field (the size inputs); multi-line
+ // editors such as the comment draft handle Esc themselves.
+ const escapeFromInput = event.key === 'Escape' && event.target instanceof HTMLInputElement;
+ if (isTypingTarget(event.target) && !escapeFromInput) return;
+ if (isOutsideViewer(event.target)) return;
+
+ if (event.key === 'Escape' && onEscape) {
+ event.preventDefault();
+ onEscape();
+ } else if (
+ event.key === 'Enter' &&
+ onEnter &&
+ !event.shiftKey &&
+ !isControlTarget(event.target)
+ ) {
+ event.preventDefault();
+ onEnter();
+ } else if (event.key.toLowerCase() === 'z' && (event.metaKey || event.ctrlKey) && onUndo) {
+ event.preventDefault();
+ onUndo();
+ }
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, []);
+};
diff --git a/src/features/FileViewer/Renderer/Image/TopBar.tsx b/src/features/FileViewer/Renderer/Image/TopBar.tsx
new file mode 100644
index 00000000000..b4a8e1d0b34
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/TopBar.tsx
@@ -0,0 +1,157 @@
+'use client';
+
+import { ActionIcon, Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import {
+ DownloadIcon,
+ MaximizeIcon,
+ MinimizeIcon,
+ RotateCwIcon,
+ XIcon,
+ ZoomInIcon,
+ ZoomOutIcon,
+} from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { MAX_ZOOM, MIN_ZOOM } from './geometry';
+
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ pointer-events: none;
+
+ position: absolute;
+ z-index: 3;
+ inset-block-start: 8px;
+ inset-inline: 8px;
+
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+ `,
+ group: css`
+ pointer-events: auto;
+
+ display: flex;
+ gap: 2px;
+ align-items: center;
+
+ padding: 2px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowTertiary};
+ `,
+ zoomLabel: css`
+ min-width: 56px;
+ padding-inline: 4px;
+ font-variant-numeric: tabular-nums;
+ `,
+}));
+
+interface TopBarProps {
+ /** A save is in flight; leaving now would lose its result, so Close waits. */
+ closeDisabled?: boolean;
+ isFullscreen: boolean;
+ onClose?: () => void;
+ onDownload: () => void;
+ onFit: () => void;
+ onRotate: () => void;
+ onToggleFullscreen: () => void;
+ onZoomIn: () => void;
+ onZoomOut: () => void;
+ zoom: number;
+}
+
+const TopBar = ({
+ closeDisabled,
+ isFullscreen,
+ onClose,
+ onDownload,
+ onFit,
+ onRotate,
+ onToggleFullscreen,
+ onZoomIn,
+ onZoomOut,
+ zoom,
+}: TopBarProps) => {
+ const { t } = useTranslation('file');
+ const percent = `${Math.round(zoom * 100)}%`;
+
+ return (
+ <div className={styles.bar}>
+ <div aria-label={t('imageViewer.zoom')} className={styles.group} role={'toolbar'}>
+ <ActionIcon
+ aria-label={t('imageViewer.zoomOut')}
+ disabled={zoom <= MIN_ZOOM}
+ icon={ZoomOutIcon}
+ size={'small'}
+ title={t('imageViewer.zoomOut')}
+ onClick={onZoomOut}
+ />
+ <Button
+ aria-label={`${t('imageViewer.fitToScreen')} (${percent})`}
+ className={styles.zoomLabel}
+ size={'small'}
+ title={t('imageViewer.fitToScreen')}
+ type={'text'}
+ onClick={onFit}
+ >
+ {percent}
+ </Button>
+ <ActionIcon
+ aria-label={t('imageViewer.zoomIn')}
+ disabled={zoom >= MAX_ZOOM}
+ icon={ZoomInIcon}
+ size={'small'}
+ title={t('imageViewer.zoomIn')}
+ onClick={onZoomIn}
+ />
+ <ActionIcon
+ aria-label={t('imageViewer.rotate')}
+ icon={RotateCwIcon}
+ size={'small'}
+ title={t('imageViewer.rotate')}
+ onClick={onRotate}
+ />
+ </div>
+ <div aria-label={t('imageViewer.fileActions')} className={styles.group} role={'toolbar'}>
+ <ActionIcon
+ aria-label={t('imageViewer.download')}
+ icon={DownloadIcon}
+ size={'small'}
+ title={t('imageViewer.download')}
+ onClick={onDownload}
+ />
+ <ActionIcon
+ aria-label={isFullscreen ? t('imageViewer.exitFullscreen') : t('imageViewer.fullscreen')}
+ icon={isFullscreen ? MinimizeIcon : MaximizeIcon}
+ size={'small'}
+ title={isFullscreen ? t('imageViewer.exitFullscreen') : t('imageViewer.fullscreen')}
+ onClick={onToggleFullscreen}
+ />
+ {(onClose || isFullscreen) && (
+ <ActionIcon
+ aria-label={t('imageViewer.close')}
+ disabled={closeDisabled && !isFullscreen}
+ icon={XIcon}
+ size={'small'}
+ title={t('imageViewer.close')}
+ onClick={() => {
+ // In browser full screen the close button leaves full screen first,
+ // so the host panel is visible again before it closes.
+ if (isFullscreen) {
+ onToggleFullscreen();
+ return;
+ }
+ onClose?.();
+ }}
+ />
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default TopBar;
diff --git a/src/features/FileViewer/Renderer/Image/VersionSwitcher.tsx b/src/features/FileViewer/Renderer/Image/VersionSwitcher.tsx
new file mode 100644
index 00000000000..47222723107
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/VersionSwitcher.tsx
@@ -0,0 +1,76 @@
+'use client';
+
+import { Button } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { useTranslation } from 'react-i18next';
+
+import type { ImageVersion } from './context';
+
+const styles = createStaticStyles(({ css }) => ({
+ bar: css`
+ position: absolute;
+ z-index: 3;
+ inset-block-start: 48px;
+ inset-inline-start: 8px;
+
+ overflow-x: auto;
+ display: flex;
+ gap: 2px;
+ align-items: center;
+
+ max-width: calc(100% - 16px);
+ padding: 2px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgElevated};
+ box-shadow: ${cssVar.boxShadowTertiary};
+ `,
+ item: css`
+ flex-shrink: 0;
+ `,
+}));
+
+interface VersionSwitcherProps {
+ /** Version on stage; `undefined` means the original. */
+ activeId?: string;
+ onSelect: (fileId?: string) => void;
+ versions: ImageVersion[];
+}
+
+/** Switch the stage between the original and the edits saved in this session. */
+const VersionSwitcher = ({ activeId, onSelect, versions }: VersionSwitcherProps) => {
+ const { t } = useTranslation('file');
+
+ const items = [
+ { id: undefined, label: t('imageViewer.version.original'), title: undefined },
+ ...versions.map((version) => ({
+ id: version.fileId,
+ label: t(`imageViewer.tool.${version.operation}`),
+ title: version.name,
+ })),
+ ];
+
+ return (
+ <div aria-label={t('imageViewer.version.label')} className={styles.bar} role={'toolbar'}>
+ {items.map((item) => {
+ const selected = item.id === activeId;
+ return (
+ <Button
+ aria-pressed={selected}
+ className={styles.item}
+ key={item.id ?? 'original'}
+ size={'small'}
+ title={item.title}
+ type={selected ? 'primary' : 'text'}
+ onClick={() => onSelect(item.id)}
+ >
+ {item.label}
+ </Button>
+ );
+ })}
+ </div>
+ );
+};
+
+export default VersionSwitcher;
diff --git a/src/features/FileViewer/Renderer/Image/context.ts b/src/features/FileViewer/Renderer/Image/context.ts
new file mode 100644
index 00000000000..b3d54354a47
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/context.ts
@@ -0,0 +1,62 @@
+import { createContext, use } from 'react';
+
+import type { DerivedImageOperation, Point, Rotation, Size } from './geometry';
+import type { ImageMarkup } from './Tools/markup';
+
+/** Room a tool panel takes on the right or at the bottom, in pixels. */
+export interface StageReserve {
+ bottom?: number;
+ right?: number;
+}
+
+/** An edit saved from this viewer, shown next to the original for comparison. */
+export interface ImageVersion {
+ fileId: string;
+ name: string;
+ operation: DerivedImageOperation;
+ url: string;
+}
+
+/**
+ * What the viewer shares with mounted tools: the file identity, the displayed
+ * image geometry, and the element tools draw over. Tools own their own state;
+ * the viewer only exposes the stage.
+ */
+export interface ImageStageValue {
+ /** Register a saved edit and show it on stage; the original stays one click away. */
+ addVersion: (version: ImageVersion) => void;
+ /** The viewer is narrow: tool bars show icons only so they stay on one line. */
+ compact: boolean;
+ fileId: string;
+ /** Lets a tool ask the viewer to fit the image back on screen. */
+ fitToScreen: () => void;
+ /**
+ * Unsent annotations and comments for the version on stage. The viewer keeps
+ * them per version in memory, so switching versions does not drop them and
+ * closing the viewer does.
+ */
+ markup: ImageMarkup;
+ name?: string;
+ /** Natural pixel size, known once the image has loaded. */
+ naturalSize?: Size;
+ /** Element covering the displayed (rotated, zoomed) image; tools portal overlays into it. */
+ overlayElement: HTMLDivElement | null;
+ rotation: Rotation;
+ /** A tool marks a save it cannot abort, so the viewer keeps Close disabled meanwhile. */
+ setBusy: (busy: boolean) => void;
+ setMarkup: (markup: ImageMarkup | ((current: ImageMarkup) => ImageMarkup)) => void;
+ /** Reserve room for a panel so the image shrinks instead of being covered. */
+ setReserve: (reserve: StageReserve) => void;
+ /** Map a pointer position to a normalized point on the image. */
+ toImagePoint: (client: Point) => Point | undefined;
+ url: string;
+ zoom: number;
+}
+
+export const ImageStageContext = createContext<ImageStageValue | null>(null);
+
+export const useImageStage = () => {
+ const value = use(ImageStageContext);
+ if (!value) throw new Error('useImageStage must be used inside the image viewer');
+ return value;
+};
diff --git a/src/features/FileViewer/Renderer/Image/geometry.test.ts b/src/features/FileViewer/Renderer/Image/geometry.test.ts
new file mode 100644
index 00000000000..6c5173737fc
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/geometry.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ buildDerivedFileMetadata,
+ buildDerivedFileName,
+ clampZoom,
+ clientToImagePoint,
+ fitSize,
+ imagePointToScreenFraction,
+ MAX_ZOOM,
+ MIN_ZOOM,
+ nextRotation,
+ zoomIn,
+ zoomOut,
+} from './geometry';
+
+describe('zoom helpers', () => {
+ it('steps and clamps zoom', () => {
+ expect(zoomIn(1)).toBeCloseTo(1.25);
+ expect(zoomOut(1)).toBeCloseTo(0.8);
+ expect(clampZoom(100)).toBe(MAX_ZOOM);
+ expect(clampZoom(0.01)).toBe(MIN_ZOOM);
+ expect(zoomIn(MAX_ZOOM)).toBe(MAX_ZOOM);
+ });
+
+ it('cycles rotation in quarter turns', () => {
+ expect(nextRotation(0)).toBe(90);
+ expect(nextRotation(270)).toBe(0);
+ });
+});
+
+describe('fitSize', () => {
+ it('fits a wide image into the container keeping its aspect', () => {
+ expect(fitSize({ height: 1000, width: 2000 }, { height: 500, width: 500 })).toEqual({
+ height: 250,
+ width: 500,
+ });
+ });
+
+ it('never upscales a small image at fit', () => {
+ expect(fitSize({ height: 100, width: 200 }, { height: 800, width: 800 })).toEqual({
+ height: 100,
+ width: 200,
+ });
+ });
+
+ it('fits the swapped footprint for a quarter turn', () => {
+ // 2000×1000 rotated stands 1000 wide and 2000 tall in a 500×500 box → scale 0.25.
+ expect(fitSize({ height: 1000, width: 2000 }, { height: 500, width: 500 }, 90)).toEqual({
+ height: 250,
+ width: 500,
+ });
+ });
+
+ it('returns zero size before measurements exist', () => {
+ expect(fitSize({ height: 0, width: 0 }, { height: 500, width: 500 })).toEqual({
+ height: 0,
+ width: 0,
+ });
+ });
+});
+
+describe('clientToImagePoint', () => {
+ // A 200×100 image box drawn at (100, 100).
+ const rect = { height: 100, left: 100, top: 100, width: 200 };
+
+ it('normalizes a pointer against the unrotated box', () => {
+ expect(clientToImagePoint({ x: 150, y: 125 }, rect)).toEqual({ x: 0.25, y: 0.25 });
+ });
+
+ it('clamps points outside the image', () => {
+ expect(clientToImagePoint({ x: 0, y: 500 }, rect)).toEqual({ x: 0, y: 1 });
+ });
+
+ it('undoes a 90° clockwise turn', () => {
+ // The 200×100 image turned 90° occupies a 100×200 box. Its top-left corner
+ // (0,0) is now at the box's top-right.
+ const rotated = { height: 200, left: 150, top: 50, width: 100 };
+ const topLeft = clientToImagePoint({ x: 250, y: 50 }, rotated, 90);
+ expect(topLeft.x).toBeCloseTo(0);
+ expect(topLeft.y).toBeCloseTo(0);
+ const bottomRight = clientToImagePoint({ x: 150, y: 250 }, rotated, 90);
+ expect(bottomRight.x).toBeCloseTo(1);
+ expect(bottomRight.y).toBeCloseTo(1);
+ });
+
+ it('undoes 180° and 270° turns', () => {
+ const half = clientToImagePoint({ x: 300, y: 200 }, rect, 180);
+ expect(half.x).toBeCloseTo(0);
+ expect(half.y).toBeCloseTo(0);
+
+ const rotated = { height: 200, left: 150, top: 50, width: 100 };
+ // After 270° the image's top-left corner sits at the box's bottom-left.
+ const topLeft = clientToImagePoint({ x: 150, y: 250 }, rotated, 270);
+ expect(topLeft.x).toBeCloseTo(0);
+ expect(topLeft.y).toBeCloseTo(0);
+ });
+});
+
+describe('derived file helpers', () => {
+ it('names derived images after the original', () => {
+ expect(buildDerivedFileName('sunset.jpeg', 'annotated')).toBe('sunset-annotated.png');
+ expect(buildDerivedFileName('archive.v2.webp', 'resized')).toBe('archive.v2-resized.png');
+ expect(buildDerivedFileName(undefined, 'resized')).toBe('image-resized.png');
+ });
+
+ it('records lineage without touching the source', () => {
+ expect(buildDerivedFileMetadata('file_1', 'resize')).toEqual({
+ derivedFrom: { fileId: 'file_1', operation: 'resize' },
+ });
+ });
+});
+
+describe('imagePointToScreenFraction', () => {
+ it('follows the image corner around each quarter turn', () => {
+ const topLeft = { x: 0, y: 0 };
+ expect(imagePointToScreenFraction(topLeft, 0)).toEqual({ x: 0, y: 0 });
+ expect(imagePointToScreenFraction(topLeft, 90)).toEqual({ x: 1, y: 0 });
+ expect(imagePointToScreenFraction(topLeft, 180)).toEqual({ x: 1, y: 1 });
+ expect(imagePointToScreenFraction(topLeft, 270)).toEqual({ x: 0, y: 1 });
+ });
+
+ it('puts a lower-left image point near the top after a 90° turn', () => {
+ // The sea's top-left corner sits low in the image but near the top on screen.
+ const screen = imagePointToScreenFraction({ x: 0.07, y: 0.75 }, 90);
+ expect(screen.x).toBeCloseTo(0.25);
+ expect(screen.y).toBeCloseTo(0.07);
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/geometry.ts b/src/features/FileViewer/Renderer/Image/geometry.ts
new file mode 100644
index 00000000000..3d31ca99861
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/geometry.ts
@@ -0,0 +1,144 @@
+export interface Size {
+ height: number;
+ width: number;
+}
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+/** A rectangle in image space, normalized to 0–1 against the natural size. */
+export interface NormalizedRect {
+ height: number;
+ width: number;
+ x: number;
+ y: number;
+}
+
+/** Quarter turns only; the viewer rotates in 90° steps. */
+export type Rotation = 0 | 90 | 180 | 270;
+
+/** Zoom is relative to the "fit" size, so 1 always means the whole image is visible. */
+export const MIN_ZOOM = 0.25;
+export const MAX_ZOOM = 8;
+export const ZOOM_STEP = 1.25;
+
+export const clamp = (value: number, min: number, max: number) =>
+ Math.min(max, Math.max(min, value));
+
+export const clampZoom = (zoom: number) => clamp(zoom, MIN_ZOOM, MAX_ZOOM);
+
+export const zoomIn = (zoom: number) => clampZoom(zoom * ZOOM_STEP);
+
+export const zoomOut = (zoom: number) => clampZoom(zoom / ZOOM_STEP);
+
+export const nextRotation = (rotation: Rotation): Rotation => ((rotation + 90) % 360) as Rotation;
+
+export const isQuarterTurn = (rotation: Rotation) => rotation === 90 || rotation === 270;
+
+/**
+ * Size of the (unrotated) image box that fits the container at zoom 1. A
+ * quarter-turned image swaps its footprint, so the fit is computed against the
+ * swapped natural size and the box keeps the image's own aspect.
+ */
+export const fitSize = (natural: Size, container: Size, rotation: Rotation = 0): Size => {
+ if (natural.width <= 0 || natural.height <= 0 || container.width <= 0 || container.height <= 0)
+ return { height: 0, width: 0 };
+
+ const footprint = isQuarterTurn(rotation)
+ ? { height: natural.width, width: natural.height }
+ : natural;
+ // Never upscale past 100% at fit: a small image stays crisp at its real size.
+ const scale = Math.min(1, container.width / footprint.width, container.height / footprint.height);
+
+ return { height: natural.height * scale, width: natural.width * scale };
+};
+
+/**
+ * Map a pointer position to a normalized point on the image. `rect` is the
+ * on-screen bounding box of the rotated image element (what
+ * `getBoundingClientRect` returns); CSS rotates clockwise around the center, so
+ * the pointer offset is turned back counter-clockwise before normalizing.
+ */
+export const clientToImagePoint = (
+ client: Point,
+ rect: { height: number; left: number; top: number; width: number },
+ rotation: Rotation = 0,
+): Point => {
+ const dx = client.x - (rect.left + rect.width / 2);
+ const dy = client.y - (rect.top + rect.height / 2);
+
+ let local: Point;
+ switch (rotation) {
+ case 90: {
+ local = { x: dy, y: -dx };
+ break;
+ }
+ case 180: {
+ local = { x: -dx, y: -dy };
+ break;
+ }
+ case 270: {
+ local = { x: -dy, y: dx };
+ break;
+ }
+ default: {
+ local = { x: dx, y: dy };
+ }
+ }
+
+ const box = isQuarterTurn(rotation)
+ ? { height: rect.width, width: rect.height }
+ : { height: rect.height, width: rect.width };
+
+ if (box.width <= 0 || box.height <= 0) return { x: 0, y: 0 };
+
+ return {
+ x: clamp(local.x / box.width + 0.5, 0, 1),
+ y: clamp(local.y / box.height + 0.5, 0, 1),
+ };
+};
+
+/**
+ * Where a normalized image point lands within the rotated image's on-screen
+ * box (also 0–1). Used to keep popovers on the side of a point that has room.
+ */
+export const imagePointToScreenFraction = (point: Point, rotation: Rotation = 0): Point => {
+ switch (rotation) {
+ case 90: {
+ return { x: 1 - point.y, y: point.x };
+ }
+ case 180: {
+ return { x: 1 - point.x, y: 1 - point.y };
+ }
+ case 270: {
+ return { x: point.y, y: 1 - point.x };
+ }
+ default: {
+ return point;
+ }
+ }
+};
+
+/** `photo.jpeg` + `annotated` → `photo-annotated.png` */
+export const buildDerivedFileName = (name: string | undefined, suffix: string, ext = 'png') => {
+ const base = (name || 'image').replace(/\.[^./\\]+$/, '') || 'image';
+ return `${base}-${suffix}.${ext}`;
+};
+
+export type DerivedImageOperation = 'erase' | 'removeBackground' | 'resize';
+
+export const DERIVED_FILE_SUFFIX: Record<DerivedImageOperation, string> = {
+ erase: 'erased',
+ removeBackground: 'no-bg',
+ resize: 'resized',
+};
+
+/** Lineage recorded on a derived file; the original is never overwritten. */
+export const buildDerivedFileMetadata = (
+ sourceFileId: string,
+ operation: DerivedImageOperation,
+) => ({
+ derivedFrom: { fileId: sourceFileId, operation },
+});
diff --git a/src/features/FileViewer/Renderer/Image/index.test.tsx b/src/features/FileViewer/Renderer/Image/index.test.tsx
new file mode 100644
index 00000000000..f8f3735cadf
--- /dev/null
+++ b/src/features/FileViewer/Renderer/Image/index.test.tsx
@@ -0,0 +1,304 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useImageStage } from './context';
+import ImageViewer from './index';
+
+const downloadFile = vi.hoisted(() => vi.fn());
+vi.mock('@/utils/client/downloadFile', () => ({ downloadFile }));
+
+const confirmModal = vi.hoisted(() => vi.fn());
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ confirmModal,
+}));
+
+const loadImage = (width = 2000, height = 1000) => {
+ const img = document.querySelector('img') as HTMLImageElement;
+ Object.defineProperty(img, 'naturalWidth', { configurable: true, value: width });
+ Object.defineProperty(img, 'naturalHeight', { configurable: true, value: height });
+ fireEvent.load(img);
+ return img;
+};
+
+const AddVersionProbe = () => {
+ const { addVersion } = useImageStage();
+ return (
+ <button
+ onClick={() =>
+ addVersion({
+ fileId: 'file_nobg',
+ name: 'sunset-no-bg.png',
+ operation: 'removeBackground',
+ url: 'https://s3/sunset-no-bg.png',
+ })
+ }
+ >
+ add-version
+ </button>
+ );
+};
+
+const StageProbe = () => {
+ const stage = useImageStage();
+ return (
+ <div data-testid={'probe'}>
+ {stage.fileId}:{stage.naturalSize?.width}x{stage.naturalSize?.height}:{stage.zoom}
+ </div>
+ );
+};
+
+describe('ImageViewer', () => {
+ beforeEach(() => downloadFile.mockReset());
+
+ it('renders the top bar with zoom, download and full screen', () => {
+ render(<ImageViewer fileId={'file_1'} name={'sunset.png'} url={'https://s3/sunset.png'} />);
+
+ expect(screen.getByRole('button', { name: 'imageViewer.zoomOut' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'imageViewer.zoomIn' })).toBeInTheDocument();
+ expect(
+ screen.getByRole('button', { name: /imageViewer.fitToScreen \(100%\)/ }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'imageViewer.download' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'imageViewer.fullscreen' })).toBeInTheDocument();
+ // No host close action → no close button outside full screen.
+ expect(screen.queryByRole('button', { name: 'imageViewer.close' })).not.toBeInTheDocument();
+ });
+
+ it('shows the host close action when provided', () => {
+ const onClose = vi.fn();
+ render(<ImageViewer fileId={'file_1'} url={'https://s3/a.png'} onClose={onClose} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.close' }));
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it('zooms with buttons and keyboard, and fits back to 100%', () => {
+ render(<ImageViewer fileId={'file_1'} url={'https://s3/a.png'} />);
+ loadImage();
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.zoomIn' }));
+ expect(screen.getByRole('button', { name: /\(125%\)/ })).toBeInTheDocument();
+
+ fireEvent.keyDown(screen.getByTestId('image-viewer'), { key: '+' });
+ expect(screen.getByRole('button', { name: /\(156%\)/ })).toBeInTheDocument();
+
+ fireEvent.keyDown(screen.getByTestId('image-viewer'), { key: '0' });
+ expect(screen.getByRole('button', { name: /\(100%\)/ })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.zoomOut' }));
+ expect(screen.getByRole('button', { name: /\(80%\)/ })).toBeInTheDocument();
+ });
+
+ it('downloads the original file', () => {
+ render(<ImageViewer fileId={'file_1'} name={'sunset.png'} url={'https://s3/sunset.png'} />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.download' }));
+ expect(downloadFile).toHaveBeenCalledWith('https://s3/sunset.png', 'sunset.png');
+ });
+
+ it('mounts the tools slot only after the image loads, with stage context', () => {
+ render(<ImageViewer fileId={'file_1'} tools={<StageProbe />} url={'https://s3/a.png'} />);
+
+ expect(screen.queryByTestId('probe')).not.toBeInTheDocument();
+ loadImage(640, 480);
+ expect(screen.getByTestId('probe')).toHaveTextContent('file_1:640x480:1');
+ });
+
+ it('shows an error with retry when the image fails to load', () => {
+ render(<ImageViewer fileId={'file_1'} tools={<StageProbe />} url={'https://s3/broken.png'} />);
+
+ fireEvent.error(document.querySelector('img')!);
+ expect(screen.getByText('imageViewer.loadFailed')).toBeInTheDocument();
+ expect(screen.queryByTestId('probe')).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('imageViewer.retry'));
+ expect(screen.queryByText('imageViewer.loadFailed')).not.toBeInTheDocument();
+ });
+
+ it('shows a saved edit on stage and switches back to the original', () => {
+ render(
+ <ImageViewer
+ fileId={'file_1'}
+ name={'sunset.png'}
+ url={'https://s3/sunset.png'}
+ tools={
+ <>
+ <AddVersionProbe />
+ <StageProbe />
+ </>
+ }
+ />,
+ );
+ loadImage(640, 480);
+ expect(screen.queryByRole('toolbar', { name: 'imageViewer.version.label' })).toBeNull();
+
+ fireEvent.click(screen.getByText('add-version'));
+ expect(document.querySelector('img')).toHaveAttribute('src', 'https://s3/sunset-no-bg.png');
+ loadImage(640, 480);
+ // Tools now act on the edit, so a follow-up edit chains from it.
+ expect(screen.getByTestId('probe')).toHaveTextContent('file_nobg:640x480:1');
+
+ const original = screen.getByRole('button', { name: 'imageViewer.version.original' });
+ const edit = screen.getByRole('button', { name: 'imageViewer.tool.removeBackground' });
+ expect(edit).toHaveAttribute('aria-pressed', 'true');
+ expect(edit).toHaveAttribute('title', 'sunset-no-bg.png');
+
+ fireEvent.click(original);
+ expect(document.querySelector('img')).toHaveAttribute('src', 'https://s3/sunset.png');
+ loadImage(640, 480);
+ expect(screen.getByTestId('probe')).toHaveTextContent('file_1:640x480:1');
+ expect(original).toHaveAttribute('aria-pressed', 'true');
+
+ // Download follows the version on stage.
+ fireEvent.click(edit);
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.download' }));
+ expect(downloadFile).toHaveBeenCalledWith('https://s3/sunset-no-bg.png', 'sunset-no-bg.png');
+ });
+
+ // Regression: the tools remount while a version loads, which dropped the
+ // unsent annotations and comments kept inside them.
+ it('keeps unsent marks per version across version switches', () => {
+ const MarkupProbe = () => {
+ const { markup, setMarkup } = useImageStage();
+ return (
+ <button
+ onClick={() =>
+ setMarkup({
+ ...markup,
+ comments: [
+ ...markup.comments,
+ { anchor: { point: { x: 0.5, y: 0.5 }, type: 'point' }, id: 'c1', text: 'hi' },
+ ],
+ })
+ }
+ >
+ {`marks:${markup.comments.length}`}
+ </button>
+ );
+ };
+ render(
+ <ImageViewer
+ fileId={'file_1'}
+ url={'https://s3/sunset.png'}
+ tools={
+ <>
+ <AddVersionProbe />
+ <MarkupProbe />
+ </>
+ }
+ />,
+ );
+ loadImage();
+ fireEvent.click(screen.getByText('marks:0'));
+ expect(screen.getByText('marks:1')).toBeInTheDocument();
+
+ // A saved edit goes on stage: its own marks start empty.
+ fireEvent.click(screen.getByText('add-version'));
+ loadImage();
+ expect(screen.getByText('marks:0')).toBeInTheDocument();
+
+ // Back on the original, its marks are still there.
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.version.original' }));
+ loadImage();
+ expect(screen.getByText('marks:1')).toBeInTheDocument();
+ });
+
+ // Unsent marks exist only in the viewer, so closing asks before dropping them.
+ it('confirms before closing with unsent marks', () => {
+ const MarkProbe = () => {
+ const { setMarkup } = useImageStage();
+ return (
+ <button
+ onClick={() =>
+ setMarkup({
+ comments: [],
+ shapes: [{ color: '#f00', points: [], size: 0.01, type: 'brush' }],
+ })
+ }
+ >
+ mark
+ </button>
+ );
+ };
+ const onClose = vi.fn();
+ render(
+ <ImageViewer
+ fileId={'file_1'}
+ tools={<MarkProbe />}
+ url={'https://s3/a.png'}
+ onClose={onClose}
+ />,
+ );
+ loadImage();
+ fireEvent.click(screen.getByText('mark'));
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.close' }));
+
+ expect(onClose).not.toHaveBeenCalled();
+ expect(confirmModal).toHaveBeenCalledWith(
+ expect.objectContaining({ title: 'imageViewer.markup.discardConfirm.title' }),
+ );
+ confirmModal.mock.calls[0][0].onOk();
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ // Regression: the host Close stayed enabled during a save that cannot be
+ // aborted, so the result landed in a viewer that no longer existed.
+ it('disables Close while a tool reports a save in flight', () => {
+ const BusyProbe = () => {
+ const { setBusy } = useImageStage();
+ return <button onClick={() => setBusy(true)}>busy</button>;
+ };
+ const onClose = vi.fn();
+ render(
+ <ImageViewer
+ fileId={'file_1'}
+ tools={<BusyProbe />}
+ url={'https://s3/a.png'}
+ onClose={onClose}
+ />,
+ );
+ loadImage();
+ fireEvent.click(screen.getByText('busy'));
+
+ const close = screen.getByRole('button', { name: 'imageViewer.close' });
+ fireEvent.click(close);
+ expect(onClose).not.toHaveBeenCalled();
+ });
+
+ it('shrinks the stage by the room a tool panel reserves', () => {
+ const ReserveProbe = () => {
+ const { setReserve } = useImageStage();
+ return <button onClick={() => setReserve({ right: 300 })}>reserve</button>;
+ };
+ render(<ImageViewer fileId={'file_1'} tools={<ReserveProbe />} url={'https://s3/a.png'} />);
+ loadImage();
+ fireEvent.click(screen.getByText('reserve'));
+
+ const stage = document.querySelector('img')!.closest('[style*="inset"]') as HTMLElement;
+ expect(stage.style.insetInlineEnd).toBe('300px');
+ });
+
+ it('drops saved versions when another file opens', () => {
+ const { rerender } = render(
+ <ImageViewer fileId={'file_1'} tools={<AddVersionProbe />} url={'https://s3/a.png'} />,
+ );
+ loadImage();
+ fireEvent.click(screen.getByText('add-version'));
+ expect(screen.getByRole('toolbar', { name: 'imageViewer.version.label' })).toBeInTheDocument();
+
+ rerender(
+ <ImageViewer fileId={'file_2'} tools={<AddVersionProbe />} url={'https://s3/b.png'} />,
+ );
+ expect(document.querySelector('img')).toHaveAttribute('src', 'https://s3/b.png');
+ expect(screen.queryByRole('toolbar', { name: 'imageViewer.version.label' })).toBeNull();
+ });
+
+ it('renders nothing without a url', () => {
+ const { container } = render(<ImageViewer fileId={'file_1'} url={null} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/src/features/FileViewer/Renderer/Image/index.tsx b/src/features/FileViewer/Renderer/Image/index.tsx
index 99a3bd1d439..d0c687cf678 100644
--- a/src/features/FileViewer/Renderer/Image/index.tsx
+++ b/src/features/FileViewer/Renderer/Image/index.tsx
@@ -1,37 +1,473 @@
'use client';
import { Center } from '@lobehub/ui';
-import { Spin } from '@lobehub/ui/base-ui';
-import { memo, useState } from 'react';
+import { Button, confirmModal, Spin, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import type { KeyboardEvent, PointerEvent, ReactNode } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getFileDownloadUrl } from '@/features/EditorCanvas/fileDownload';
+import { downloadFile } from '@/utils/client/downloadFile';
+
+import {
+ ImageStageContext,
+ type ImageStageValue,
+ type ImageVersion,
+ type StageReserve,
+} from './context';
+import {
+ clampZoom,
+ clientToImagePoint,
+ fitSize,
+ nextRotation,
+ type Point,
+ type Rotation,
+ type Size,
+ zoomIn,
+ zoomOut,
+} from './geometry';
+import { EMPTY_MARKUP, type ImageMarkup, isMarkupEmpty } from './Tools/markup';
+import TopBar from './TopBar';
+import VersionSwitcher from './VersionSwitcher';
+
+/** Room kept around the fitted image so the floating bars do not cover it. */
+const STAGE_PADDING = { block: 56, inline: 16 };
+
+/** Below this viewer width the tool bars switch to icons so they never wrap. */
+const COMPACT_WIDTH = 640;
+
+const styles = createStaticStyles(({ css }) => ({
+ frame: css`
+ position: absolute;
+ inset-block-start: 50%;
+ inset-inline-start: 50%;
+ `,
+ image: css`
+ user-select: none;
+
+ display: block;
+
+ width: 100%;
+ height: 100%;
+
+ -webkit-user-drag: none;
+ `,
+ overlay: css`
+ position: absolute;
+ inset: 0;
+ `,
+ root: css`
+ position: relative;
+
+ overflow: hidden;
+
+ width: 100%;
+ height: 100%;
+ min-height: 240px;
+
+ background: ${cssVar.colorFillQuaternary};
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimaryBorder};
+ outline-offset: -2px;
+ }
+ `,
+ stage: css`
+ touch-action: none;
+ position: absolute;
+ inset: 0;
+ `,
+}));
interface ImageViewerProps {
fileId: string;
+ name?: string;
+ /** Host close action; shown in the top bar when provided. */
+ onClose?: () => void;
+ /**
+ * Editing tools slot. Hosts that allow editing mount the tools atom here;
+ * read-only hosts (e.g. an unsent chat attachment) leave it empty.
+ */
+ tools?: ReactNode;
url: string | null;
}
-const ImageViewer = memo<ImageViewerProps>(({ url }) => {
- const [isLoaded, setIsLoaded] = useState(false);
+const isTypingTarget = (target: EventTarget | null) =>
+ target instanceof HTMLElement &&
+ (target.isContentEditable || ['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName));
+
+const ImageViewer = ({
+ fileId: sourceId,
+ name: sourceName,
+ onClose,
+ tools,
+ url: sourceUrl,
+}: ImageViewerProps) => {
+ const { t } = useTranslation('file');
+ const rootRef = useRef<HTMLDivElement>(null);
+ const stageRef = useRef<HTMLDivElement>(null);
+ const panStart = useRef<{ pan: Point; pointer: Point } | null>(null);
+
+ const [overlayElement, setOverlayElement] = useState<HTMLDivElement | null>(null);
+ const [status, setStatus] = useState<'error' | 'loaded' | 'loading'>('loading');
+ const [attempt, setAttempt] = useState(0);
+ const [naturalSize, setNaturalSize] = useState<Size>();
+ const [container, setContainer] = useState<Size>({ height: 0, width: 0 });
+ const [rootWidth, setRootWidth] = useState(0);
+ // Room a tool panel (the comment list) takes beside or below the image; the
+ // stage shrinks by it so the panel never covers the picture.
+ const [reserve, setReserve] = useState<StageReserve>({});
+ const [zoom, setZoom] = useState(1);
+ const [rotation, setRotation] = useState<Rotation>(0);
+ const [pan, setPan] = useState<Point>({ x: 0, y: 0 });
+ const [isFullscreen, setIsFullscreen] = useState(false);
+
+ // Edits saved in this session, keyed by the original so a new file starts clean.
+ const [versionState, setVersionState] = useState<{
+ activeId?: string;
+ sourceId: string;
+ versions: ImageVersion[];
+ }>({ sourceId, versions: [] });
+ const { activeId, versions } =
+ versionState.sourceId === sourceId ? versionState : { activeId: undefined, versions: [] };
+ const active = versions.find((version) => version.fileId === activeId);
+ const fileId = active?.fileId ?? sourceId;
+ const name = active?.name ?? sourceName;
+ const url = active?.url ?? sourceUrl;
+
+ // Unsent marks per version, outside the tools so a version switch (which
+ // remounts them while the new image loads) keeps them.
+ const [markupByFile, setMarkupByFile] = useState<Record<string, ImageMarkup>>({});
+ const [busy, setBusy] = useState(false);
+ const markup = markupByFile[fileId] ?? EMPTY_MARKUP;
+ const setMarkup = useCallback(
+ (next: ImageMarkup | ((current: ImageMarkup) => ImageMarkup)) =>
+ setMarkupByFile((state) => ({
+ ...state,
+ [fileId]: typeof next === 'function' ? next(state[fileId] ?? EMPTY_MARKUP) : next,
+ })),
+ [fileId],
+ );
+
+ const selectVersion = (id?: string) => {
+ if (id === active?.fileId) return;
+ setStatus('loading');
+ setVersionState({ activeId: id, sourceId, versions });
+ };
+
+ const addVersion = useCallback(
+ (version: ImageVersion) => {
+ setVersionState((state) => {
+ const current = state.sourceId === sourceId ? state : { sourceId, versions: [] };
+ return {
+ activeId: version.fileId,
+ sourceId,
+ versions: [...current.versions.filter((v) => v.fileId !== version.fileId), version],
+ };
+ });
+ setStatus('loading');
+ },
+ [sourceId],
+ );
+
+ // Track the stage size so "fit" follows panel resizes and full screen.
+ useEffect(() => {
+ const stage = stageRef.current;
+ if (!stage) return;
+ const measure = () => {
+ setContainer({ height: stage.clientHeight, width: stage.clientWidth });
+ setRootWidth(rootRef.current?.clientWidth ?? stage.clientWidth);
+ };
+ measure();
+ if (!('ResizeObserver' in window)) return;
+ const observer = new ResizeObserver(measure);
+ observer.observe(stage);
+ if (rootRef.current) observer.observe(rootRef.current);
+ return () => observer.disconnect();
+ }, []);
+
+ useEffect(() => {
+ const onChange = () => setIsFullscreen(document.fullscreenElement === rootRef.current);
+ document.addEventListener('fullscreenchange', onChange);
+ return () => document.removeEventListener('fullscreenchange', onChange);
+ }, []);
- if (!url) return null;
+ const fitToScreen = useCallback(() => {
+ setZoom(1);
+ setPan({ x: 0, y: 0 });
+ }, []);
+
+ const applyZoom = useCallback((next: number) => {
+ const zoomValue = clampZoom(next);
+ setZoom(zoomValue);
+ // Panning only makes sense while the image is larger than the stage.
+ if (zoomValue <= 1) setPan({ x: 0, y: 0 });
+ }, []);
+
+ // Ctrl/⌘ + wheel zooms, plain wheel pans a zoomed image. Registered natively
+ // because React's wheel listener is passive and cannot prevent page scroll.
+ const zoomRef = useRef(zoom);
+ useEffect(() => {
+ zoomRef.current = zoom;
+ }, [zoom]);
+
+ useEffect(() => {
+ const stage = stageRef.current;
+ if (!stage) return;
+ const onWheel = (event: WheelEvent) => {
+ if (event.ctrlKey || event.metaKey) {
+ event.preventDefault();
+ applyZoom(zoomRef.current * Math.exp(-event.deltaY * 0.01));
+ return;
+ }
+ if (zoomRef.current <= 1) return;
+ event.preventDefault();
+ setPan((p) => ({ x: p.x - event.deltaX, y: p.y - event.deltaY }));
+ };
+ stage.addEventListener('wheel', onWheel, { passive: false });
+ return () => stage.removeEventListener('wheel', onWheel);
+ }, [applyZoom]);
+
+ const toggleFullscreen = useCallback(() => {
+ const root = rootRef.current;
+ if (!root) return;
+ if (document.fullscreenElement) void document.exitFullscreen();
+ else void root.requestFullscreen?.();
+ }, []);
+
+ // Unsent marks exist only here, so closing would drop them; ask first.
+ const handleClose = () => {
+ if (!onClose || busy) return;
+ const hasMarks = Object.values(markupByFile).some((value) => !isMarkupEmpty(value));
+ if (!hasMarks) return onClose();
+ confirmModal({
+ cancelText: t('imageViewer.cancel'),
+ content: t('imageViewer.markup.discardConfirm.content'),
+ okButtonProps: { danger: true },
+ okText: t('imageViewer.markup.discardConfirm.ok'),
+ onOk: onClose,
+ title: t('imageViewer.markup.discardConfirm.title'),
+ });
+ };
+
+ const handleDownload = () => {
+ if (!url) return;
+ // The `/f/:id` proxy redirects to storage without CORS, so a blob download
+ // cannot read it; its `download=1` answer carries an attachment disposition.
+ const downloadUrl = getFileDownloadUrl(url, { appOrigin: window.location.origin });
+ if (downloadUrl !== url) {
+ window.open(downloadUrl, '_blank', 'noopener,noreferrer');
+ return;
+ }
+ void downloadFile(url, name || 'image');
+ };
+
+ const box = useMemo(() => {
+ if (!naturalSize) return { height: 0, width: 0 };
+ const fit = fitSize(
+ naturalSize,
+ {
+ height: Math.max(0, container.height - STAGE_PADDING.block * 2),
+ width: Math.max(0, container.width - STAGE_PADDING.inline * 2),
+ },
+ rotation,
+ );
+ return { height: fit.height * zoom, width: fit.width * zoom };
+ }, [container, naturalSize, rotation, zoom]);
+
+ const toImagePoint = useCallback(
+ (client: Point) => {
+ if (!overlayElement) return;
+ return clientToImagePoint(client, overlayElement.getBoundingClientRect(), rotation);
+ },
+ [overlayElement, rotation],
+ );
+
+ const compact = rootWidth > 0 && rootWidth < COMPACT_WIDTH;
+
+ const stageValue = useMemo<ImageStageValue | null>(
+ () =>
+ url
+ ? {
+ addVersion,
+ compact,
+ fileId,
+ fitToScreen,
+ markup,
+ name,
+ naturalSize,
+ overlayElement,
+ rotation,
+ setBusy,
+ setMarkup,
+ setReserve,
+ toImagePoint,
+ url,
+ zoom,
+ }
+ : null,
+ [
+ addVersion,
+ compact,
+ fileId,
+ fitToScreen,
+ markup,
+ name,
+ naturalSize,
+ overlayElement,
+ rotation,
+ setMarkup,
+ toImagePoint,
+ url,
+ zoom,
+ ],
+ );
+
+ if (!url || !stageValue) return null;
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (isTypingTarget(event.target) || event.metaKey || event.ctrlKey || event.altKey) return;
+ switch (event.key) {
+ case '+':
+ case '=': {
+ applyZoom(zoomIn(zoom));
+ break;
+ }
+ case '-': {
+ applyZoom(zoomOut(zoom));
+ break;
+ }
+ case '0': {
+ fitToScreen();
+ break;
+ }
+ default: {
+ return;
+ }
+ }
+ event.preventDefault();
+ };
+
+ const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {
+ if (zoom <= 1 || event.button !== 0) return;
+ panStart.current = { pan, pointer: { x: event.clientX, y: event.clientY } };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ };
+
+ const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {
+ const start = panStart.current;
+ if (!start) return;
+ setPan({
+ x: start.pan.x + event.clientX - start.pointer.x,
+ y: start.pan.y + event.clientY - start.pointer.y,
+ });
+ };
+
+ const endPan = () => {
+ panStart.current = null;
+ };
return (
- <Center height={'100%'} width={'100%'}>
- {!isLoaded && <Spin size="large" />}
- {}
- <img
- alt="Image preview"
- src={url}
- style={{
- display: isLoaded ? 'block' : 'none',
- height: '100%',
- objectFit: 'contain',
- overflow: 'hidden',
- width: '100%',
- }}
- onLoad={() => setIsLoaded(true)}
- />
- </Center>
+ <ImageStageContext value={stageValue}>
+ <div
+ aria-label={name}
+ aria-roledescription={'image viewer'}
+ className={styles.root}
+ data-testid={'image-viewer'}
+ ref={rootRef}
+ role={'region'}
+ tabIndex={0}
+ onKeyDown={handleKeyDown}
+ >
+ <div
+ className={styles.stage}
+ ref={stageRef}
+ style={{
+ cursor: zoom > 1 ? 'grab' : undefined,
+ insetBlockEnd: reserve.bottom ?? 0,
+ insetInlineEnd: reserve.right ?? 0,
+ }}
+ onPointerCancel={endPan}
+ onPointerDown={handlePointerDown}
+ onPointerMove={handlePointerMove}
+ onPointerUp={endPan}
+ >
+ <div
+ className={styles.frame}
+ style={{
+ height: box.height,
+ transform: `translate(-50%, -50%) translate(${pan.x}px, ${pan.y}px) rotate(${rotation}deg)`,
+ visibility: status === 'loaded' ? 'visible' : 'hidden',
+ width: box.width,
+ }}
+ >
+ <img
+ alt={name || 'image'}
+ className={styles.image}
+ draggable={false}
+ key={`${url}:${attempt}`}
+ src={url}
+ onError={() => setStatus('error')}
+ onLoad={(event) => {
+ const img = event.currentTarget;
+ setNaturalSize({ height: img.naturalHeight, width: img.naturalWidth });
+ setStatus('loaded');
+ }}
+ />
+ <div
+ className={styles.overlay}
+ data-testid={'image-viewer-overlay'}
+ ref={setOverlayElement}
+ />
+ </div>
+ </div>
+
+ {status === 'loading' && (
+ <Center height={'100%'} style={{ inset: 0, position: 'absolute' }} width={'100%'}>
+ <Spin size="large" />
+ </Center>
+ )}
+ {status === 'error' && (
+ <Center
+ gap={12}
+ height={'100%'}
+ style={{ inset: 0, position: 'absolute' }}
+ width={'100%'}
+ >
+ <Text type={'secondary'}>{t('imageViewer.loadFailed')}</Text>
+ <Button
+ onClick={() => {
+ setStatus('loading');
+ setAttempt((value) => value + 1);
+ }}
+ >
+ {t('imageViewer.retry')}
+ </Button>
+ </Center>
+ )}
+
+ <TopBar
+ closeDisabled={busy}
+ isFullscreen={isFullscreen}
+ zoom={zoom}
+ onClose={onClose && handleClose}
+ onDownload={handleDownload}
+ onFit={fitToScreen}
+ onRotate={() => setRotation(nextRotation)}
+ onToggleFullscreen={toggleFullscreen}
+ onZoomIn={() => applyZoom(zoomIn(zoom))}
+ onZoomOut={() => applyZoom(zoomOut(zoom))}
+ />
+
+ {versions.length > 0 && (
+ <VersionSwitcher activeId={active?.fileId} versions={versions} onSelect={selectVersion} />
+ )}
+
+ {status === 'loaded' && tools}
+ </div>
+ </ImageStageContext>
);
-});
+};
export default ImageViewer;
diff --git a/src/features/FileViewer/__tests__/imageToolHosts.test.tsx b/src/features/FileViewer/__tests__/imageToolHosts.test.tsx
new file mode 100644
index 00000000000..d11d8e90c56
--- /dev/null
+++ b/src/features/FileViewer/__tests__/imageToolHosts.test.tsx
@@ -0,0 +1,86 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { FileListItem } from '@/types/files';
+
+/** Records what each host hands to the shared viewer. */
+const viewerProps = vi.hoisted(() => [] as Array<Record<string, unknown>>);
+
+vi.mock('@/features/FileViewer', () => ({
+ default: (props: { imageTools?: ReactNode } & Record<string, unknown>) => {
+ viewerProps.push(props);
+ return <div data-testid={'file-viewer'}>{props.imageTools}</div>;
+ },
+}));
+vi.mock('@/features/FileViewer/ImageEditTools', () => ({
+ default: () => <div data-testid={'image-edit-tools'} />,
+}));
+
+const file: FileListItem = {
+ chunkCount: null,
+ chunkingError: null,
+ createdAt: new Date(),
+ embeddingError: null,
+ fileId: 'file_img',
+ fileType: 'image/png',
+ finishEmbedding: false,
+ id: 'docs_img',
+ name: 'sunset.png',
+ size: 10,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ url: 'https://s3/sunset.png',
+};
+
+vi.mock('@/store/file', () => ({
+ fileManagerSelectors: { getFileById: () => () => file },
+ useFileStore: (selector: (s: unknown) => unknown) =>
+ selector({ useFetchKnowledgeItem: () => ({ data: file }) }),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: unknown) => unknown) =>
+ selector({ activeTopicId: 'tpc_1', chunkText: undefined, previewFileId: 'file_img' }),
+}));
+vi.mock('@/store/chat/selectors', () => ({
+ chatPortalSelectors: {
+ chunkText: (s: { chunkText?: string }) => s.chunkText,
+ previewFileId: (s: { previewFileId?: string }) => s.previewFileId,
+ },
+}));
+
+describe('image tool hosts', () => {
+ it('resource detail panel mounts the editing tools on the real file id', async () => {
+ const { default: FilePreview } =
+ await import('@/features/ResourceManager/components/Explorer/FileDetailPanel/FilePreview');
+ viewerProps.length = 0;
+ render(<FilePreview file={file} />);
+
+ expect(screen.getByTestId('image-edit-tools')).toBeInTheDocument();
+ expect(viewerProps.at(-1)).toMatchObject({ id: 'file_img' });
+ });
+
+ it('full-screen resource editor mounts the tools and forwards close', async () => {
+ const { default: FileContent } =
+ await import('@/features/ResourceManager/components/Editor/FileContent');
+ const onClose = vi.fn();
+ viewerProps.length = 0;
+ render(<FileContent fileId={'file_img'} onClose={onClose} />);
+
+ expect(screen.getByTestId('image-edit-tools')).toBeInTheDocument();
+ expect(viewerProps.at(-1)).toMatchObject({ onClose });
+ });
+
+ it('conversation portal file preview mounts the tools', async () => {
+ const { default: PortalFilePreview } = await import('@/features/Portal/FilePreview/Body');
+ viewerProps.length = 0;
+ render(<PortalFilePreview />);
+
+ expect(screen.getByTestId('image-edit-tools')).toBeInTheDocument();
+ expect(viewerProps.at(-1)).toMatchObject({ id: 'docs_img', name: 'sunset.png' });
+ });
+});
diff --git a/src/features/FileViewer/imageViewer.entries.test.tsx b/src/features/FileViewer/imageViewer.entries.test.tsx
new file mode 100644
index 00000000000..d306c2ef236
--- /dev/null
+++ b/src/features/FileViewer/imageViewer.entries.test.tsx
@@ -0,0 +1,104 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render, screen } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import type { FileListItem } from '@/types/files';
+
+import FileViewer from './index';
+import { useImageStage } from './Renderer/Image/context';
+
+const baseFile: FileListItem = {
+ chunkCount: null,
+ chunkingError: null,
+ createdAt: new Date(),
+ embeddingError: null,
+ fileType: 'image/png',
+ finishEmbedding: false,
+ id: 'file_img',
+ name: 'sunset.png',
+ size: 10,
+ sourceType: 'file',
+ updatedAt: new Date(),
+ url: 'https://s3/sunset.png',
+};
+
+const Tools = () => <div data-file-id={useImageStage().fileId} data-testid={'tools'} />;
+
+const loadImage = () => {
+ const img = document.querySelector('img')!;
+ Object.defineProperty(img, 'naturalWidth', { configurable: true, value: 400 });
+ Object.defineProperty(img, 'naturalHeight', { configurable: true, value: 300 });
+ fireEvent.load(img);
+};
+
+describe('FileViewer image entry', () => {
+ it('routes images to the image viewer with the host tools and close action', () => {
+ const onClose = vi.fn();
+ render(<FileViewer {...baseFile} imageTools={<Tools />} onClose={onClose} />);
+ loadImage();
+
+ expect(screen.getByTestId('image-viewer')).toHaveAttribute('aria-label', 'sunset.png');
+ expect(screen.getByTestId('tools')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.close' }));
+ expect(onClose).toHaveBeenCalled();
+ });
+
+ // Regression: a document-coalesced item's `id` is `docs_*`; the tools must
+ // work on the persisted `file_*` behind it.
+ it('gives the tools the backing file id of a document item', () => {
+ render(
+ <FileViewer {...baseFile} fileId={'file_backing'} id={'docs_item'} imageTools={<Tools />} />,
+ );
+ loadImage();
+
+ expect(screen.getByTestId('tools')).toHaveAttribute('data-file-id', 'file_backing');
+ });
+
+ // Regression: the `/f/:id` proxy redirects to storage without CORS, so a
+ // blob download would only open the inline preview.
+ it('downloads a proxied file through the attachment route', () => {
+ const open = vi.spyOn(window, 'open').mockReturnValue(null);
+ render(<FileViewer {...baseFile} url={'https://app.lobehub.com/f/file_img'} />);
+ loadImage();
+
+ fireEvent.click(screen.getByRole('button', { name: 'imageViewer.download' }));
+
+ expect(open).toHaveBeenCalledWith(
+ 'https://app.lobehub.com/f/file_img?download=1',
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ open.mockRestore();
+ });
+
+ it('keeps read-only hosts (no tools) free of editing UI', () => {
+ render(<FileViewer {...baseFile} />);
+ loadImage();
+
+ expect(screen.getByTestId('image-viewer')).toBeInTheDocument();
+ expect(screen.queryByTestId('tools')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'imageViewer.download' })).toBeInTheDocument();
+ });
+
+ it('matches images by extension when the MIME type is generic', () => {
+ render(<FileViewer {...baseFile} fileType={'application/octet-stream'} name={'photo.webp'} />);
+ expect(screen.getByTestId('image-viewer')).toBeInTheDocument();
+ });
+
+ it('does not render image tools for non-image files', () => {
+ render(
+ <FileViewer
+ {...baseFile}
+ fileType={'video/mp4'}
+ imageTools={<Tools />}
+ name={'clip.mp4'}
+ url={'https://s3/clip.mp4'}
+ />,
+ );
+
+ expect(screen.queryByTestId('image-viewer')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('tools')).not.toBeInTheDocument();
+ });
+});
diff --git a/src/features/FileViewer/index.tsx b/src/features/FileViewer/index.tsx
index e4fa74e44dd..f32c319a8d6 100644
--- a/src/features/FileViewer/index.tsx
+++ b/src/features/FileViewer/index.tsx
@@ -3,7 +3,7 @@
import { MARKDOWN_MIME_TYPES } from '@lobechat/const';
import { Center } from '@lobehub/ui';
import { Spin } from '@lobehub/ui/base-ui';
-import type { CSSProperties, JSXElementConstructor } from 'react';
+import type { CSSProperties, JSXElementConstructor, ReactNode } from 'react';
import { memo, useCallback, useEffect, useState } from 'react';
import AsyncError from '@/components/AsyncError';
@@ -101,6 +101,13 @@ const matchesFileType = (
interface FileViewerProps extends FileListItem {
className?: string;
+ /**
+ * Editing tools for image files (`ImageEditTools`). Only hosts that show a
+ * persisted library file mount them; omit for read-only previews.
+ */
+ imageTools?: ReactNode;
+ /** Host close action, surfaced in the image viewer's top bar. */
+ onClose?: () => void;
style?: CSSProperties;
}
@@ -143,7 +150,8 @@ const usePDFRenderer = (enabled: boolean) => {
/**
* Preview any file type.
*/
-const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) => {
+const FileViewer = memo<FileViewerProps>((props) => {
+ const { id, style, fileType, url, name, imageTools, onClose } = props;
const isPDF = isPdfFile({ fileName: name, fileType, path: url });
const { retry: retryPDFRenderer, state: pdfRendererState } = usePDFRenderer(isPDF);
@@ -170,7 +178,18 @@ const FileViewer = memo<FileViewerProps>(({ id, style, fileType, url, name }) =>
// Image files
if (matchesFileType(fileType, name, IMAGE_EXTENSIONS, IMAGE_MIME_TYPES)) {
- return <ImageViewer fileId={id} url={url} />;
+ return (
+ <ImageViewer
+ // A document-coalesced item carries a `docs_*` id; the tools need the
+ // persisted file behind it.
+ fileId={props.fileId ?? id}
+ key={url}
+ name={name}
+ tools={imageTools}
+ url={url}
+ onClose={onClose}
+ />
+ );
}
// Video files
diff --git a/src/features/Portal/FilePreview/Body/index.tsx b/src/features/Portal/FilePreview/Body/index.tsx
index d73fa0371c4..f945f0bb130 100644
--- a/src/features/Portal/FilePreview/Body/index.tsx
+++ b/src/features/Portal/FilePreview/Body/index.tsx
@@ -8,6 +8,7 @@ import AsyncError from '@/components/AsyncError';
import Loading from '@/components/Loading/CircleLoading';
import FileNotFound from '@/features/FileNotFound';
import FileViewer from '@/features/FileViewer';
+import ImageEditTools from '@/features/FileViewer/ImageEditTools';
import { normalizeAsyncError } from '@/libs/swr/normalizeError';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
@@ -89,7 +90,7 @@ const FilePreview = () => {
<Markdown style={{ overflow: 'scroll', paddingInline: 8 }}>{chunkText}</Markdown>
) : (
<Flexbox flex={1} paddingBlock={8} style={{ overflow: 'scroll' }}>
- <FileViewer {...data} />
+ <FileViewer {...data} imageTools={<ImageEditTools />} />
</Flexbox>
)}
</Flexbox>
diff --git a/src/features/ResourceManager/components/Editor/FileContent.tsx b/src/features/ResourceManager/components/Editor/FileContent.tsx
index bd01b959b78..616ce909aab 100644
--- a/src/features/ResourceManager/components/Editor/FileContent.tsx
+++ b/src/features/ResourceManager/components/Editor/FileContent.tsx
@@ -4,13 +4,15 @@ import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import FileViewer from '@/features/FileViewer';
+import ImageEditTools from '@/features/FileViewer/ImageEditTools';
import { fileManagerSelectors, useFileStore } from '@/store/file';
interface FilePreviewerProps {
fileId?: string;
+ onClose?: () => void;
}
-const FilePreviewer = memo<FilePreviewerProps>(({ fileId }) => {
+const FilePreviewer = memo<FilePreviewerProps>(({ fileId, onClose }) => {
const useFetchKnowledgeItem = useFileStore((s) => s.useFetchKnowledgeItem);
const { data: fetchedFile } = useFetchKnowledgeItem(fileId);
const file = useFileStore(fileManagerSelectors.getFileById(fileId));
@@ -22,7 +24,7 @@ const FilePreviewer = memo<FilePreviewerProps>(({ fileId }) => {
return (
<Flexbox height={'100%'} width={'100%'}>
<Flexbox flex={1} height={'100%'} style={{ overflow: 'auto' }}>
- <FileViewer {...displayFile} />
+ <FileViewer {...displayFile} imageTools={<ImageEditTools />} onClose={onClose} />
</Flexbox>
</Flexbox>
);
diff --git a/src/features/ResourceManager/components/Editor/index.tsx b/src/features/ResourceManager/components/Editor/index.tsx
index 5a09d0d3c04..e2fed92fe1b 100644
--- a/src/features/ResourceManager/components/Editor/index.tsx
+++ b/src/features/ResourceManager/components/Editor/index.tsx
@@ -118,7 +118,7 @@ const FileEditorCanvas = memo<FileEditorProps>(({ onBack }) => {
}}
/>
<Flexbox flex={1} style={{ minHeight: 0, overflow: 'hidden' }}>
- <FileContent fileId={currentViewItemId} />
+ <FileContent fileId={currentViewItemId} onClose={onBack} />
</Flexbox>
</Flexbox>
</Flexbox>
diff --git a/src/features/ResourceManager/components/Explorer/FileDetailPanel/FilePreview.tsx b/src/features/ResourceManager/components/Explorer/FileDetailPanel/FilePreview.tsx
index 42b9af6cc9b..663afcec2f5 100644
--- a/src/features/ResourceManager/components/Explorer/FileDetailPanel/FilePreview.tsx
+++ b/src/features/ResourceManager/components/Explorer/FileDetailPanel/FilePreview.tsx
@@ -5,6 +5,7 @@ import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import FileViewer from '@/features/FileViewer';
+import ImageEditTools from '@/features/FileViewer/ImageEditTools';
import { type FileListItem } from '@/types/files';
interface FilePreviewProps {
@@ -25,7 +26,7 @@ const FilePreview = memo<FilePreviewProps>(({ file }) => {
</Center>
);
- return <FileViewer {...file} id={file.fileId ?? file.id} />;
+ return <FileViewer {...file} id={file.fileId ?? file.id} imageTools={<ImageEditTools />} />;
});
export default FilePreview;
diff --git a/src/services/file/index.ts b/src/services/file/index.ts
index bac28fd0fb2..fecd472756e 100644
--- a/src/services/file/index.ts
+++ b/src/services/file/index.ts
@@ -55,6 +55,12 @@ export class FileService {
};
};
+ /** Storage URL a canvas can read (no `/f/:id` redirect); see the router for why. */
+ getReadableUrl = async (id: string): Promise<string> => {
+ const { url } = await lambdaClient.file.getReadableUrl.query({ id });
+ return url;
+ };
+
removeFile = async (id: string): Promise<void> => {
await lambdaClient.file.removeFile.mutate({ id });
};