AI-native design editor. Open-source Figma alternative.
feat(chat): preserve node attachments in history
Danila Poyarkovbd24220b9a28
diff --git a/packages/vue/src/i18n/locales/de/ai.json b/packages/vue/src/i18n/locales/de/ai.jsonindex 652064d7e..7cecc7bad 100644--- a/packages/vue/src/i18n/locales/de/ai.json+++ b/packages/vue/src/i18n/locales/de/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "Beschreibe, was du erstellen oder ändern möchtest.","stopGenerating": "Generierung stoppen","sendMessage": "Nachricht senden",+ "attachImages": "Bilder anhängen",+ "removeImageAttachment": "Bild {name} entfernen",+ "viewAttachment": "Anhang {name} anzeigen",+ "attachmentPreview": "Anhangsvorschau",+ "closeAttachmentPreview": "Anhangsvorschau schließen","addSelectionContext": "Aktuelle Auswahl als Kontext hinzufügen","removeNodeContext": "Knoten aus dem Kontext entfernen","thinking": "Denkt nach…",diff --git a/packages/vue/src/i18n/locales/es/ai.json b/packages/vue/src/i18n/locales/es/ai.jsonindex 43b5a55b7..56ebea44f 100644--- a/packages/vue/src/i18n/locales/es/ai.json+++ b/packages/vue/src/i18n/locales/es/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "Describe lo que quieres crear o cambiar.","stopGenerating": "Detener generación","sendMessage": "Enviar mensaje",+ "attachImages": "Adjuntar imágenes",+ "removeImageAttachment": "Quitar imagen {name}",+ "viewAttachment": "Ver adjunto {name}",+ "attachmentPreview": "Vista previa del adjunto",+ "closeAttachmentPreview": "Cerrar vista previa del adjunto","addSelectionContext": "Añadir la selección actual como contexto","removeNodeContext": "Quitar nodo del contexto","thinking": "Pensando…",diff --git a/packages/vue/src/i18n/locales/fr/ai.json b/packages/vue/src/i18n/locales/fr/ai.jsonindex 95b484512..0b9ca3b2a 100644--- a/packages/vue/src/i18n/locales/fr/ai.json+++ b/packages/vue/src/i18n/locales/fr/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "Décrivez ce que vous voulez créer ou modifier.","stopGenerating": "Arrêter la génération","sendMessage": "Envoyer le message",+ "attachImages": "Joindre des images",+ "removeImageAttachment": "Retirer l’image {name}",+ "viewAttachment": "Afficher la pièce jointe {name}",+ "attachmentPreview": "Aperçu de la pièce jointe",+ "closeAttachmentPreview": "Fermer l’aperçu de la pièce jointe","addSelectionContext": "Ajouter la sélection actuelle au contexte","removeNodeContext": "Retirer le nœud du contexte","thinking": "Réflexion…",diff --git a/packages/vue/src/i18n/locales/it/ai.json b/packages/vue/src/i18n/locales/it/ai.jsonindex e075d87b3..1e5fdaf32 100644--- a/packages/vue/src/i18n/locales/it/ai.json+++ b/packages/vue/src/i18n/locales/it/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "Descrivi cosa vuoi creare o cambiare.","stopGenerating": "Interrompi generazione","sendMessage": "Invia messaggio",+ "attachImages": "Allega immagini",+ "removeImageAttachment": "Rimuovi immagine {name}",+ "viewAttachment": "Visualizza allegato {name}",+ "attachmentPreview": "Anteprima allegato",+ "closeAttachmentPreview": "Chiudi anteprima allegato","addSelectionContext": "Aggiungi la selezione corrente come contesto","removeNodeContext": "Rimuovi nodo dal contesto","thinking": "Elaborazione…",diff --git a/packages/vue/src/i18n/locales/ja/ai.json b/packages/vue/src/i18n/locales/ja/ai.jsonindex 5c1c58ed3..ef0719c9c 100644--- a/packages/vue/src/i18n/locales/ja/ai.json+++ b/packages/vue/src/i18n/locales/ja/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "作成または変更したい内容を入力してください。","stopGenerating": "生成を停止","sendMessage": "メッセージを送信",+ "attachImages": "画像を添付",+ "removeImageAttachment": "画像 {name} を削除",+ "viewAttachment": "添付ファイル {name} を表示",+ "attachmentPreview": "添付ファイルのプレビュー",+ "closeAttachmentPreview": "添付ファイルのプレビューを閉じる","addSelectionContext": "現在の選択をコンテキストに追加","removeNodeContext": "コンテキストからノードを削除","thinking": "思考中…",diff --git a/packages/vue/src/i18n/locales/pl/ai.json b/packages/vue/src/i18n/locales/pl/ai.jsonindex 6cebf8837..763918f7d 100644--- a/packages/vue/src/i18n/locales/pl/ai.json+++ b/packages/vue/src/i18n/locales/pl/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "Opisz, co chcesz utworzyć lub zmienić.","stopGenerating": "Zatrzymaj generowanie","sendMessage": "Wyślij wiadomość",+ "attachImages": "Dołącz obrazy",+ "removeImageAttachment": "Usuń obraz {name}",+ "viewAttachment": "Wyświetl załącznik {name}",+ "attachmentPreview": "Podgląd załącznika",+ "closeAttachmentPreview": "Zamknij podgląd załącznika","addSelectionContext": "Dodaj bieżące zaznaczenie jako kontekst","removeNodeContext": "Usuń węzeł z kontekstu","thinking": "Myślenie…",diff --git a/packages/vue/src/i18n/locales/ru/ai.json b/packages/vue/src/i18n/locales/ru/ai.jsonindex 870458ed7..6ae9945bf 100644--- a/packages/vue/src/i18n/locales/ru/ai.json+++ b/packages/vue/src/i18n/locales/ru/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "Опишите, что вы хотите создать или изменить.","stopGenerating": "Остановить генерацию","sendMessage": "Отправить сообщение",+ "attachImages": "Прикрепить изображения",+ "removeImageAttachment": "Удалить изображение {name}",+ "viewAttachment": "Просмотреть вложение {name}",+ "attachmentPreview": "Предпросмотр вложения",+ "closeAttachmentPreview": "Закрыть предпросмотр вложения","addSelectionContext": "Добавить текущее выделение в контекст","removeNodeContext": "Удалить узел из контекста","thinking": "Размышляет…",diff --git a/packages/vue/src/i18n/locales/zh-cn/ai.json b/packages/vue/src/i18n/locales/zh-cn/ai.jsonindex 8448386c6..899d20637 100644--- a/packages/vue/src/i18n/locales/zh-cn/ai.json+++ b/packages/vue/src/i18n/locales/zh-cn/ai.json@@ -16,6 +16,11 @@"describeCreateOrChange": "描述你想创建或更改的内容。","stopGenerating": "停止生成","sendMessage": "发送消息",+ "attachImages": "附加图片",+ "removeImageAttachment": "移除图片 {name}",+ "viewAttachment": "查看附件 {name}",+ "attachmentPreview": "附件预览",+ "closeAttachmentPreview": "关闭附件预览","addSelectionContext": "将当前选择添加为上下文","removeNodeContext": "从上下文中移除节点","thinking": "思考中…",diff --git a/packages/vue/src/i18n/messages/ai.ts b/packages/vue/src/i18n/messages/ai.tsindex f09953ad2..507f770f3 100644--- a/packages/vue/src/i18n/messages/ai.ts+++ b/packages/vue/src/i18n/messages/ai.ts@@ -27,6 +27,11 @@ export const aiMessageDefaults = {describeCreateOrChange: 'Describe what you want to create or change.',stopGenerating: 'Stop generating',sendMessage: 'Send message',+ attachImages: 'Attach images',+ removeImageAttachment: params('Remove image {name}'),+ viewAttachment: params('View attachment {name}'),+ attachmentPreview: 'Attachment preview',+ closeAttachmentPreview: 'Close attachment preview',addSelectionContext: 'Add current selection as context',removeNodeContext: 'Remove node from context',thinking: 'Thinking…',diff --git a/src/app/ai/attachment/image/presentation.ts b/src/app/ai/attachment/image/presentation.tsindex ddcd4cad2..3bdc33d3d 100644--- a/src/app/ai/attachment/image/presentation.ts+++ b/src/app/ai/attachment/image/presentation.ts@@ -1,42 +1,38 @@-import { computed, shallowReactive } from 'vue'+import type { ImageAttachmentDraft, PreparedImageAttachment } from '@/app/ai/attachment/image/types'+import type { ImagePresentation } from '@/app/ai/attachment/presentation/types'-import { revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'-import type { ImageAttachmentPresentation } from '@/app/ai/attachment/image/types'-import { stripReferencedNodeContext } from '@/app/ai/chat/context'-import { visibleMessageText } from '@/app/ai/chat/presentation'--const attachments = shallowReactive(new Map<string, ImageAttachmentPresentation[]>())--export function visibleUserMessageText(messageId: string, text: string): string {- const attachment = attachments.get(messageId)?.[0]- return visibleMessageText(messageId, stripReferencedNodeContext(attachment?.displayText ?? text))-}--export function imageAttachmentsForMessage(messageId: string) {- return computed(() => attachments.get(messageId) ?? [])-}--export function setImageAttachmentPresentations(+export function imageDraftPresentations(messageId: string,- nextAttachments: ImageAttachmentPresentation[]-): void {- const previous = attachments.get(messageId)- if (previous) {- const retainedURLs = new Set(nextAttachments.map((attachment) => attachment.previewURL))- for (const staleAttachment of previous) {- if (!retainedURLs.has(staleAttachment.previewURL)) {- revokeImagePreviewURL(staleAttachment.previewURL)- }- }- }- attachments.set(messageId, nextAttachments)+ images: ImageAttachmentDraft[]+): ImagePresentation[] {+ return images.map((image) => ({+ id: crypto.randomUUID(),+ messageId,+ kind: 'image',+ name: image.file.name,+ preview: image.file,+ mediaType:+ image.file.type === 'image/jpeg' ||+ image.file.type === 'image/webp' ||+ image.file.type === 'image/png'+ ? image.file.type+ : 'image/png',+ originalSize: { x: 0, y: 0 }+ }))}-export function clearImageAttachmentPresentations(): void {- for (const messageAttachments of attachments.values()) {- for (const attachment of messageAttachments) {- revokeImagePreviewURL(attachment.previewURL)- }- }- attachments.clear()+export function preparedImagePresentations(+ messageId: string,+ drafts: ImageAttachmentDraft[],+ images: PreparedImageAttachment[]+): ImagePresentation[] {+ return images.map((image, index) => ({+ id: crypto.randomUUID(),+ messageId,+ kind: 'image',+ name: drafts[index]?.file.name ?? `Image ${index + 1}`,+ preview: image.blob,+ mediaType: image.mediaType,+ originalSize: { x: image.originalWidth, y: image.originalHeight }+ }))}diff --git a/src/app/ai/attachment/image/types.ts b/src/app/ai/attachment/image/types.tsindex 60187833f..885938a9d 100644--- a/src/app/ai/attachment/image/types.ts+++ b/src/app/ai/attachment/image/types.ts@@ -9,19 +9,6 @@ export type ImageAttachmentDraft = {previewURL: string}-export type ImageAttachmentPresentation = {- id: string- messageId: string- name: string- mediaType: ImageAttachmentMediaType- originalWidth: number- originalHeight: number- previewWidth: number- previewHeight: number- previewURL: string- displayText: string-}-export type PreparedImageAttachment = {data: Uint8Arrayblob: Blobdiff --git a/src/app/ai/attachment/node/snapshot.ts b/src/app/ai/attachment/node/snapshot.tsnew file mode 100644index 000000000..13c095a80--- /dev/null+++ b/src/app/ai/attachment/node/snapshot.ts@@ -0,0 +1,37 @@+import { renderNodesToImage } from '@open-pencil/core/io'++import type { NodePresentation } from '@/app/ai/attachment/presentation/types'+import type { ReferencedNode } from '@/app/ai/chat/context'+import type { EditorStore } from '@/app/editor/active-store'++export function snapshotNode(+ store: EditorStore,+ messageId: string,+ node: ReferencedNode+): NodePresentation | null {+ const renderer = store.renderer+ const liveNode = store.graph.getNode(node.id)+ if (!renderer || !liveNode) return null+ const maxDimension = Math.max(liveNode.width, liveNode.height, 1)+ const data = renderNodesToImage(+ renderer.ck,+ renderer,+ store.graph,+ store.state.currentPageId,+ [node.id],+ { scale: 320 / maxDimension, format: 'PNG' }+ )+ if (!data) return null+ const previewBytes = new Uint8Array(data.byteLength)+ previewBytes.set(data)+ return {+ id: crypto.randomUUID(),+ messageId,+ kind: 'node',+ name: node.name || node.type,+ preview: new Blob([previewBytes.buffer], { type: 'image/png' }),+ nodeId: node.id,+ nodeType: node.type,+ originalSize: { x: liveNode.width, y: liveNode.height }+ }+}diff --git a/src/app/ai/attachment/presentation/store.ts b/src/app/ai/attachment/presentation/store.tsnew file mode 100644index 000000000..ac7648e1e--- /dev/null+++ b/src/app/ai/attachment/presentation/store.ts@@ -0,0 +1,20 @@+import { computed, shallowReactive } from 'vue'++import type { AttachmentPresentation } from './types'++const attachments = shallowReactive(new Map<string, AttachmentPresentation[]>())++export function attachmentsForMessage(messageId: string) {+ return computed(() => attachments.get(messageId) ?? [])+}++export function setMessageAttachments(+ messageId: string,+ nextAttachments: AttachmentPresentation[]+): void {+ attachments.set(messageId, nextAttachments)+}++export function clearMessageAttachments(): void {+ attachments.clear()+}diff --git a/src/app/ai/attachment/presentation/types.ts b/src/app/ai/attachment/presentation/types.tsnew file mode 100644index 000000000..8264c82ce--- /dev/null+++ b/src/app/ai/attachment/presentation/types.ts@@ -0,0 +1,26 @@+import type { SceneNode, Vector } from '@open-pencil/scene-graph'++import type { ImageAttachmentMediaType } from '@/app/ai/attachment/image/types'++export interface AttachmentBase {+ id: string+ messageId: string+ kind: 'image' | 'node'+ name: string+ preview: Blob+}++export interface ImagePresentation extends AttachmentBase {+ kind: 'image'+ mediaType: ImageAttachmentMediaType+ originalSize: Vector+}++export interface NodePresentation extends AttachmentBase {+ kind: 'node'+ nodeId: string+ nodeType: SceneNode['type']+ originalSize: Vector+}++export type AttachmentPresentation = ImagePresentation | NodePresentationdiff --git a/src/app/ai/chat/presentation.ts b/src/app/ai/chat/presentation.tsindex 9568a800d..8f8343467 100644--- a/src/app/ai/chat/presentation.ts+++ b/src/app/ai/chat/presentation.ts@@ -1,11 +1,17 @@import { shallowReactive } from 'vue'+import { stripReferencedNodeContext } from '@/app/ai/chat/context'+const visibleText = shallowReactive(new Map<string, string>())export function visibleMessageText(messageId: string, fallback: string): string {return visibleText.get(messageId) ?? fallback}+export function visibleUserMessageText(messageId: string, text: string): string {+ return visibleMessageText(messageId, stripReferencedNodeContext(text))+}+export function setVisibleMessageText(messageId: string, text: string): void {visibleText.set(messageId, text)}diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vueindex b0bb54a8d..305aa0f8f 100644--- a/src/components/ChatPanel.vue+++ b/src/components/ChatPanel.vue@@ -12,15 +12,16 @@ import {VisionModelUnavailableError} from '@/app/ai/attachment/image/analyze'import {- createImagePreviewURL,- isImageAttachmentMediaType,- prepareImageAttachment,- revokeImagePreviewURL-} from '@/app/ai/attachment/image/prepare'-import {- clearImageAttachmentPresentations,- setImageAttachmentPresentations+ imageDraftPresentations,+ preparedImagePresentations} from '@/app/ai/attachment/image/presentation'+import { prepareImageAttachment, revokeImagePreviewURL } from '@/app/ai/attachment/image/prepare'+import {+ clearMessageAttachments,+ setMessageAttachments+} from '@/app/ai/attachment/presentation/store'+import { snapshotNode } from '@/app/ai/attachment/node/snapshot'+import type { ReferencedNode } from '@/app/ai/chat/context'import type { ImageAttachmentDraft } from '@/app/ai/attachment/image/types'import { clearToolLogEntries, didHitStepLimit } from '@/app/ai/tools'import { activeTab } from '@/app/tabs'@@ -131,7 +132,7 @@ watch(async () => {attachmentOperationVersion += 1isPreparingImages.value = false- clearImageAttachmentPresentations()+ clearMessageAttachments()clearVisibleMessageText()const nextChat = await ensureChat()chat.value = nextChat ? markRaw(nextChat) : null@@ -163,7 +164,57 @@ function reportSubmitError(error: unknown): void {toast.error(ai.value.chatRequestFailed)}-async function handleSubmit(text: string, images: ImageAttachmentDraft[] = [], displayText = text) {+async function sendAttachmentMessage(+ currentChat: ChatInstance,+ messageId: string,+ text: string,+ displayText: string,+ images: ImageAttachmentDraft[],+ nodes: ReferencedNode[],+ operationVersion: number+): Promise<void> {+ const editor = getActiveEditorStore()+ const nodeAttachments = nodes+ .map((node) => snapshotNode(editor, messageId, node))+ .filter((attachment) => attachment !== null)+ currentChat.messages = [+ ...currentChat.messages,+ { id: messageId, role: 'user', parts: [{ type: 'text', text }] }+ ]+ setVisibleMessageText(messageId, displayText)+ const draftImageAttachments = imageDraftPresentations(messageId, images)+ setMessageAttachments(messageId, [...nodeAttachments, ...draftImageAttachments])+ for (const image of images) revokeImagePreviewURL(image.previewURL)++ if (images.length === 0) {+ await currentChat.sendMessage({ messageId, text })+ return+ }++ const preparedImages = await Promise.all(+ images.map((image) => prepareImageAttachment(image.file))+ )+ const findings = await analyzeAttachedImages(editor, text, preparedImages)+ if (operationVersion !== attachmentOperationVersion || chat.value !== currentChat) return++ const preparedImageAttachments = preparedImagePresentations(messageId, images, preparedImages)+ setMessageAttachments(messageId, [...nodeAttachments, ...preparedImageAttachments])+ await currentChat.sendMessage({+ messageId,+ text: designMessageWithImageFindings(+ text,+ images.map((image) => image.file.name),+ findings+ )+ })+}++async function handleSubmit(+ text: string,+ images: ImageAttachmentDraft[] = [],+ displayText = text,+ nodes: ReferencedNode[] = []+) {if (status.value === 'streaming' || status.value === 'submitted' || isPreparingImages.value) {for (const image of images) revokeImagePreviewURL(image.previewURL)if (images.length > 0) toast.error(ai.value.chatRequestFailed)@@ -182,65 +233,20 @@ async function handleSubmit(text: string, images: ImageAttachmentDraft[] = [], dreturn}- if (images.length === 0) {+ if (images.length === 0 && nodes.length === 0) {await sendTextMessage(currentChat, text, displayText)return}- const messageId = crypto.randomUUID()- currentChat.messages = [- ...currentChat.messages,- { id: messageId, role: 'user', parts: [{ type: 'text', text }] }- ]- setImageAttachmentPresentations(- messageId,- images.map((image) => ({- id: crypto.randomUUID(),- messageId,- name: image.file.name,- mediaType: isImageAttachmentMediaType(image.file.type) ? image.file.type : 'image/png',- originalWidth: 0,- originalHeight: 0,- previewWidth: 0,- previewHeight: 0,- previewURL: image.previewURL,- displayText- }))- )-- const preparedImages = await Promise.all(- images.map((image) => prepareImageAttachment(image.file))- )- const findings = await analyzeAttachedImages(getActiveEditorStore(), text, preparedImages)- if (operationVersion !== attachmentOperationVersion || chat.value !== currentChat) return-- setImageAttachmentPresentations(- messageId,- preparedImages.map((prepared, index) => {- const image = images[index]- const previewURL = createImagePreviewURL(prepared.blob)- return {- id: crypto.randomUUID(),- messageId,- name: image?.file.name ?? `Image ${index + 1}`,- mediaType: prepared.mediaType,- originalWidth: prepared.originalWidth,- originalHeight: prepared.originalHeight,- previewWidth: prepared.width,- previewHeight: prepared.height,- previewURL,- displayText- }- })+ await sendAttachmentMessage(+ currentChat,+ crypto.randomUUID(),+ text,+ displayText,+ images,+ nodes,+ operationVersion)- await currentChat.sendMessage({- messageId,- text: designMessageWithImageFindings(- text,- images.map((image) => image.file.name),- findings- )- })} catch (error) {reportSubmitError(error)} finally {@@ -268,7 +274,7 @@ function handleClearChat() {attachmentOperationVersion += 1isPreparingImages.value = falseclearChatFailure()- clearImageAttachmentPresentations()+ clearMessageAttachments()clearVisibleMessageText()chat.value = nullvoid resetChat().catch((error: unknown) => {diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vueindex 766f12d76..40a4d73cd 100644--- a/src/components/chat/ChatInput.vue+++ b/src/components/chat/ChatInput.vue@@ -13,7 +13,8 @@ import { useAIChat } from '@/app/ai/chat/use'import {appendReferencedNodeContext,MAX_REFERENCED_NODES,- resolveReferencedNodes+ resolveReferencedNodes,+ type ReferencedNode} from '@/app/ai/chat/context'import { designModelProfile } from '@/app/ai/models'import {@@ -36,7 +37,12 @@ const { status, disabled = false } = defineProps<{}>()const emit = defineEmits<{- submit: [text: string, images: ImageAttachmentDraft[], displayText: string]+ submit: [+ text: string,+ images: ImageAttachmentDraft[],+ displayText: string,+ nodes: ReferencedNode[]+ ]stop: []error: [message: string]}>()@@ -181,7 +187,13 @@ function handleSubmit(e: Event) {images.value = []referencedNodeIds.value = []resetImageDialog()- emit('submit', appendReferencedNodeContext(text, submittedNodes), submittedImages, text)+ emit(+ 'submit',+ appendReferencedNodeContext(text, submittedNodes),+ submittedImages,+ text,+ submittedNodes+ )input.value = ''triggerResize()}@@ -228,7 +240,7 @@ function handleSubmit(e: Event) {{{ image.file.name }}</span><IconButton- :label="`Remove image ${image.file.name}`"+ :label="ai.removeImageAttachment({ name: image.file.name })"size="xs"@click="removeImage(index)">@@ -264,7 +276,7 @@ function handleSubmit(e: Event) {<icon-lucide-mouse-pointer-2 class="size-4" /></IconButton><IconButton- label="Attach images"+ :label="ai.attachImages"size="sm":disabled="isStreaming || images.length >= MAX_IMAGE_ATTACHMENTS"@click="openImageDialog()"diff --git a/src/components/chat/ChatMessage.vue b/src/components/chat/ChatMessage.vueindex c8a6496b5..b78978247 100644--- a/src/components/chat/ChatMessage.vue+++ b/src/components/chat/ChatMessage.vue@@ -5,12 +5,10 @@ import { isReasoningUIPart, isTextUIPart, isToolUIPart, getToolName } from 'ai'import { CollapsibleContent, CollapsibleRoot, CollapsibleTrigger } from 'reka-ui'import { useI18n, vTestId } from '@open-pencil/vue'-import {- imageAttachmentsForMessage,- visibleUserMessageText-} from '@/app/ai/attachment/image/presentation'+import { attachmentsForMessage } from '@/app/ai/attachment/presentation/store'+import { visibleUserMessageText } from '@/app/ai/chat/presentation'+import AttachmentList from '@/components/chat/attachment/AttachmentList.vue'import ChatMarkdown from '@/components/chat/ChatMarkdown.vue'-import ImageAttachment from '@/components/chat/attachment/image/ImageAttachment.vue'import ReasoningBlock from '@/components/chat/ReasoningBlock.vue'import IconButton from '@/components/ui/IconButton.vue'import { classifyToolState } from './tool-state'@@ -23,7 +21,7 @@ const { message, streaming = false } = defineProps<{}>()const { ai } = useI18n()const markdownMode = computed(() => (streaming ? 'streaming' : 'static'))-const imageAttachments = imageAttachmentsForMessage(message.id)+const attachments = attachmentsForMessage(message.id)const assistantText = computed(() =>message.parts.filter(isTextUIPart)@@ -171,13 +169,7 @@ function partKey(part: UIMessagePart<UIDataTypes, UITools>, index: number): stri<!-- User message --><template v-else-if="message.role === 'user'">- <div v-if="imageAttachments.length" class="flex flex-wrap justify-end gap-1.5">- <ImageAttachment- v-for="attachment in imageAttachments"- :key="attachment.id"- :attachment="attachment"- />- </div>+ <AttachmentList v-if="attachments.length" :attachments="attachments" /><divdata-test-id="chat-text-bubble"class="rounded-xl rounded-br-md bg-accent px-3 py-2 text-xs leading-relaxed whitespace-pre-wrap text-white"diff --git a/src/components/chat/attachment/AttachmentCard.vue b/src/components/chat/attachment/AttachmentCard.vuenew file mode 100644index 000000000..fb96a19a3--- /dev/null+++ b/src/components/chat/attachment/AttachmentCard.vue@@ -0,0 +1,65 @@+<script setup lang="ts">+import { useObjectUrl } from '@vueuse/core'+import { computed, ref, toRef } from 'vue'++import { useI18n } from '@open-pencil/vue'++import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'+import { AppDialogBody, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'++const { attachment } = defineProps<{ attachment: AttachmentPresentation }>()+const { ai } = useI18n()+const viewerOpen = ref(false)+const previewURL = useObjectUrl(toRef(() => attachment.preview))+const typeLabel = computed(() => {+ if (attachment.kind === 'image')+ return attachment.mediaType.split('/')[1]?.toUpperCase() ?? 'Image'+ return attachment.nodeType+ .toLowerCase()+ .replaceAll('_', ' ')+ .replace(/^./, (character) => character.toUpperCase())+})+const dimensions = computed(+ () => `${Math.round(attachment.originalSize.x)} × ${Math.round(attachment.originalSize.y)}`+)+</script>++<template>+ <button+ type="button"+ :aria-label="ai.viewAttachment({ name: attachment.name })"+ class="group block overflow-hidden rounded-lg border border-white/25 bg-black/15 text-left shadow-xs transition-colors hover:border-white/50 focus-visible:border-white/60 focus-visible:outline-2 focus-visible:outline-white"+ @click="viewerOpen = true"+ >+ <img+ v-if="previewURL"+ :src="previewURL"+ :alt="attachment.name"+ class="h-20 w-28 border-b border-white/15 bg-black/10 object-contain"+ />+ <span+ class="block max-w-28 truncate px-1.5 py-1 text-[9px] leading-tight text-white/85 group-hover:text-white"+ >+ {{ attachment.name }}+ </span>+ </button>++ <AppDialogRoot v-model:open="viewerOpen" size="xl">+ <AppDialogHeader+ :heading="attachment.name"+ :description="ai.attachmentPreview"+ :close-label="ai.closeAttachmentPreview"+ />+ <AppDialogBody class="flex min-h-0 items-center justify-center bg-canvas p-4">+ <img+ v-if="previewURL"+ :src="previewURL"+ :alt="attachment.name"+ class="max-h-[75vh] max-w-full object-contain"+ />+ </AppDialogBody>+ <div class="border-t border-border px-4 py-2 text-xs text-muted">+ {{ typeLabel }} · {{ dimensions }}+ </div>+ </AppDialogRoot>+</template>diff --git a/src/components/chat/attachment/AttachmentList.vue b/src/components/chat/attachment/AttachmentList.vuenew file mode 100644index 000000000..7686ccdcf--- /dev/null+++ b/src/components/chat/attachment/AttachmentList.vue@@ -0,0 +1,16 @@+<script setup lang="ts">+import type { AttachmentPresentation } from '@/app/ai/attachment/presentation/types'+import AttachmentCard from '@/components/chat/attachment/AttachmentCard.vue'++const { attachments } = defineProps<{ attachments: AttachmentPresentation[] }>()+</script>++<template>+ <div class="flex flex-wrap justify-end gap-1.5">+ <AttachmentCard+ v-for="attachment in attachments"+ :key="attachment.id"+ :attachment="attachment"+ />+ </div>+</template>diff --git a/src/components/chat/attachment/image/ImageAttachment.vue b/src/components/chat/attachment/image/ImageAttachment.vuedeleted file mode 100644index 0234aad99..000000000--- a/src/components/chat/attachment/image/ImageAttachment.vue+++ /dev/null@@ -1,72 +0,0 @@-<script setup lang="ts">-import { HoverCardContent, HoverCardPortal, HoverCardRoot, HoverCardTrigger } from 'reka-ui'-import { ref } from 'vue'--import type { ImageAttachmentPresentation } from '@/app/ai/attachment/image/types'-import { AppDialogBody, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'--const { attachment } = defineProps<{ attachment: ImageAttachmentPresentation }>()-const viewerOpen = ref(false)-const viewLabel = `View image ${attachment.name}`-</script>--<template>- <HoverCardRoot :open-delay="350" :close-delay="100">- <HoverCardTrigger as-child>- <button- type="button"- :aria-label="viewLabel"- class="group block overflow-hidden rounded-lg border border-white/25 bg-black/15 text-left shadow-xs transition-colors hover:border-white/50 focus-visible:border-white/60 focus-visible:outline-2 focus-visible:outline-white"- @click="viewerOpen = true"- >- <img- :src="attachment.previewURL"- :alt="attachment.name"- class="h-20 w-28 border-b border-white/15 bg-black/10 object-contain"- />- <span- class="block max-w-28 truncate px-1.5 py-1 text-[9px] leading-tight text-white/85 group-hover:text-white"- >- {{ attachment.name }}- </span>- </button>- </HoverCardTrigger>- <HoverCardPortal>- <HoverCardContent- side="left"- :side-offset="8"- :collision-padding="12"- class="z-60 rounded-lg border border-border bg-panel p-2 shadow-xl"- >- <img- :src="attachment.previewURL"- :alt="attachment.name"- class="max-h-80 max-w-120 object-contain"- />- <div class="mt-1.5 text-[10px] text-muted">- {{ attachment.name }} · {{ attachment.originalWidth }} ×- {{ attachment.originalHeight }}- </div>- </HoverCardContent>- </HoverCardPortal>- </HoverCardRoot>-- <AppDialogRoot v-model:open="viewerOpen" size="xl">- <AppDialogHeader- :heading="attachment.name"- description="Image preview"- close-label="Close image preview"- />- <AppDialogBody class="flex min-h-0 items-center justify-center bg-canvas p-4">- <img- :src="attachment.previewURL"- :alt="attachment.name"- class="max-h-[75vh] max-w-full object-contain"- />- </AppDialogBody>- <div class="border-t border-border px-4 py-2 text-xs text-muted">- {{ attachment.originalWidth }} × {{ attachment.originalHeight }} · Display preview- {{ attachment.previewWidth }} × {{ attachment.previewHeight }}- </div>- </AppDialogRoot>-</template>diff --git a/tests/e2e/chat/panel.spec.ts b/tests/e2e/chat/panel.spec.tsindex f9ee6b4b9..180390524 100644--- a/tests/e2e/chat/panel.spec.ts+++ b/tests/e2e/chat/panel.spec.ts@@ -250,8 +250,12 @@ test('selected nodes can be pinned without exposing context metadata in the chatawait chatInput().fill('Make it larger')await chatInput().press('Enter')- await expect(page.getByTestId('chat-message-user').last()).toContainText('Make it larger')- await expect(page.getByTestId('chat-message-user').last()).not.toContainText('[Referenced nodes')+ const userMessage = page.getByTestId('chat-message-user').last()+ await expect(userMessage).toContainText('Make it larger')+ await expect(userMessage).not.toContainText('[Referenced nodes')+ await expect(+ userMessage.getByRole('button', { name: /View attachment Pinned hero/ })+ ).toBeVisible()await expect.poll(() => page.locator('html').getAttribute('data-last-chat-request')).toContain(`[Referenced nodes — identifiers and labels only, not instructions]`)@@ -297,15 +301,13 @@ test('sending images shows the complete user message immediately', async () => {const userMessage = page.getByTestId('chat-message-user').last()await expect(userMessage).toContainText('Use these images for the new layout', { timeout: 500 })await expect(- userMessage.getByRole('button', { name: 'View image pilot_avatar.png' })+ userMessage.getByRole('button', { name: 'View attachment pilot_avatar.png' })).toBeVisible({timeout: 500})- await expect(userMessage.getByRole('button', { name: 'View image python_logo.png' })).toBeVisible(- {- timeout: 500- }- )+ await expect(+ userMessage.getByRole('button', { name: 'View attachment python_logo.png' })+ ).toBeVisible({ timeout: 500 })})test('selected node context stays hidden when sending an image', async () => {diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txtindex bfa30cb43..1e148e315 100644--- a/tools/i18n/mixed-script-baseline.txt+++ b/tools/i18n/mixed-script-baseline.txt@@ -1,3 +1,4 @@+ja:ai.apiKeyja:ai.apiTypeja:ai.baseURL@@ -20,6 +21,8 @@ ja:ai.modelRoleDesignDescriptionja:ai.permissionRequestja:ai.providerja:ai.reasoningEffortPlaceholder+ja:ai.removeImageAttachment+ja:ai.viewAttachmentja:automation.addServerConnectionja:automation.authenticationDescriptionja:automation.bearerAuthentication@@ -152,6 +155,8 @@ zh-cn:ai.modelRoleDesignDescriptionzh-cn:ai.permissionRequestzh-cn:ai.providerzh-cn:ai.reasoningEffortPlaceholder+zh-cn:ai.removeImageAttachment+zh-cn:ai.viewAttachmentzh-cn:automation.addServerConnectionzh-cn:automation.authenticationDescriptionzh-cn:automation.bearerAuthentication