diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 4f1d764ffef2..229ac99e3a75 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3946,9 +3946,15 @@ export default function ChatView(props: ChatViewProps) { onExpandImage={onExpandTimelineImageStable} onFileOpen={openFileAttachmentStable} editingQueuedAttachments={queuedRunEdit.editingAttachments} + removedEditingQueuedAttachments={ + queuedRunEdit.removedEditingAttachments + } onRemoveEditingQueuedAttachment={ queuedRunEdit.removeEditingAttachment } + onRestoreEditingQueuedAttachment={ + queuedRunEdit.restoreEditingAttachment + } /> )} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 402156b00128..634b7a9389e9 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -203,6 +203,8 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** True when the change came from undo or redo. */ + fromHistory?: boolean, ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; @@ -1127,6 +1129,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index af4871b45193..85a7f6173bf9 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -23,6 +23,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -120,6 +121,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -287,6 +289,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { cancelHeldComposerSend, countPreparingComposerImages, @@ -457,8 +460,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -599,7 +605,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -657,6 +665,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -757,33 +771,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -798,6 +834,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1393,12 +1431,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1447,6 +1493,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: onRestoreEditingQueuedAttachment, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1652,6 +1700,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1762,6 +1811,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + fromHistory, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1781,6 +1838,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -3814,11 +3877,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} {!isComposerCollapsedMobile && - pendingUserInputs.length === 0 && - editingQueuedAttachments !== null && - editingQueuedAttachments.length > 0 && ( + activeEditingQueuedAttachments !== null && + activeEditingQueuedAttachments.length > 0 && ( )} diff --git a/apps/web/src/components/chat/composerContextUndo.test.ts b/apps/web/src/components/chat/composerContextUndo.test.ts index a763b47a0d6d..c493aa2dfc8f 100644 --- a/apps/web/src/components/chat/composerContextUndo.test.ts +++ b/apps/web/src/components/chat/composerContextUndo.test.ts @@ -1,4 +1,8 @@ -import type { PreviewAnnotationPayload } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + type PreviewAnnotationPayload, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { ComposerImageAttachment } from "../../composerDraftStore"; @@ -37,7 +41,7 @@ const annotation = { } satisfies PreviewAnnotationPayload; function retention(): RetainedAttachmentContextPayloads { - return { files: new Map(), previewAnnotations: new Map() }; + return { files: new Map(), previewAnnotations: new Map(), restoredQueuedImageIds: new Set() }; } describe("reconcileAttachmentContextReferences", () => { @@ -88,4 +92,65 @@ describe("reconcileAttachmentContextReferences", () => { }), ]); }); + + it("drops a queued file with its chip, keeps a queued image, and lets undo and redo restore and remove either", () => { + const file = { + attachment: { + type: "file" as const, + id: ChatAttachmentId.make("server-file"), + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + contextIds: [ComposerContextId.make("file_local")], + }; + const queuedImage = { + attachment: { + type: "image" as const, + id: ChatAttachmentId.make("server-image"), + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }, + contextIds: [ComposerContextId.make("image_local")], + }; + const base = { files: [], images: [], previewAnnotations: [], retained: retention() }; + + const deleted = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + }); + expect(deleted.queuedAttachmentIdsToRemove).toEqual([file.attachment.id]); + + const undone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["file_local", "image_local"]), + removedQueuedAttachments: [file, queuedImage], + }); + expect(undone.queuedAttachmentsToRestore).toEqual([file.attachment, queuedImage.attachment]); + + const redone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + fromHistory: true, + }); + expect(redone.queuedAttachmentIdsToRemove).toEqual([ + file.attachment.id, + queuedImage.attachment.id, + ]); + + reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["image_local"]), + removedQueuedAttachments: [queuedImage], + }); + const backspaced = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [queuedImage], + }); + expect(backspaced.queuedAttachmentIdsToRemove).toEqual([]); + }); }); diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index fd2a0cde5934..4c96ec12b70f 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -1,4 +1,6 @@ import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, PreviewAnnotationPayload, ThreadContextRecord, @@ -9,15 +11,23 @@ import type { ComposerFileAttachment, ComposerImageAttachment } from "../../comp import { fileContextReference, previewAnnotationContextId } from "../../lib/composerContextRecords"; import type { TerminalContextDraft } from "../../lib/terminalContext"; import type { ReviewCommentContext } from "../../reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; interface RetainedPreviewAnnotation { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | undefined; } +export interface QueuedAttachmentContextBinding { + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; +} + export interface RetainedAttachmentContextPayloads { files: Map; previewAnnotations: Map; + /** Queued images brought back because their chip reappeared. */ + restoredQueuedImageIds: Set; } export interface RetainedContextPayloads extends RetainedAttachmentContextPayloads { @@ -35,6 +45,7 @@ function createRetainedContextPayloads(): RetainedContextPayloads { environments: new Map(), files: new Map(), previewAnnotations: new Map(), + restoredQueuedImageIds: new Set(), }; } @@ -61,12 +72,19 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont export function reconcileAttachmentContextReferences(input: { referencedContextIds: ReadonlySet; files: ReadonlyArray; + /** Attachments of a queued message being edited, and those removed during the edit. */ + queuedAttachments?: ReadonlyArray; + removedQueuedAttachments?: ReadonlyArray; + /** The change came from undo or redo. */ + fromHistory?: boolean; images: ReadonlyArray; previewAnnotations: ReadonlyArray; retained: RetainedAttachmentContextPayloads; }): { filesToRemove: string[]; filesToRestore: ComposerFileAttachment[]; + queuedAttachmentIdsToRemove: string[]; + queuedAttachmentsToRestore: ChatAttachment[]; annotationIdsToRemove: string[]; annotationsToRestore: RetainedPreviewAnnotation[]; } { @@ -86,6 +104,23 @@ export function reconcileAttachmentContextReferences(input: { return file ? [file] : []; }); + const isReferenced = (entry: QueuedAttachmentContextBinding) => + entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId)); + const restoredImageIds = input.retained.restoredQueuedImageIds; + const queuedAttachmentIdsToRemove = (input.queuedAttachments ?? []).flatMap((entry) => { + if (entry.contextIds.length === 0 || isReferenced(entry)) return []; + if (isQueuedFileAttachment(entry.attachment)) return [entry.attachment.id]; + // Like draft images, a queued image outlives its deleted chip, unless undo or redo + // takes away a chip whose return had brought the image back. + const wasRestored = restoredImageIds.delete(entry.attachment.id); + return wasRestored && input.fromHistory ? [entry.attachment.id] : []; + }); + const queuedAttachmentsToRestore = (input.removedQueuedAttachments ?? []).flatMap((entry) => { + if (!isReferenced(entry)) return []; + if (isQueuedImageAttachment(entry.attachment)) restoredImageIds.add(entry.attachment.id); + return [entry.attachment]; + }); + const imagesById = new Map(input.images.map((image) => [image.id, image])); const liveAnnotationContextIds = new Set( input.previewAnnotations.map((annotation) => previewAnnotationContextId(annotation.id)), @@ -106,5 +141,12 @@ export function reconcileAttachmentContextReferences(input: { return retained ? [retained] : []; }); - return { filesToRemove, filesToRestore, annotationIdsToRemove, annotationsToRestore }; + return { + filesToRemove, + filesToRestore, + queuedAttachmentIdsToRemove, + queuedAttachmentsToRestore, + annotationIdsToRemove, + annotationsToRestore, + }; } diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index 49d22add3a23..0ebfdacdbb60 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -1,4 +1,11 @@ -import { EnvironmentId, MessageId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + EnvironmentId, + MessageId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { beforeEach, describe, expect, it } from "vite-plus/test"; @@ -10,7 +17,12 @@ import { } from "../../composerDraftStore"; import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; import { environmentContextRecord, responseContextRecord } from "../../lib/composerContextRecords"; -import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { + matchRestorableQueuedAttachment, + prepareQueuedEditAttachments, + recoverQueuedMessageEdit, +} from "./queuedMessageEdit"; const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); @@ -193,6 +205,85 @@ describe("queued message file edits", () => { expect(store.getComposerDraft(threadTarget)).toBeNull(); }); + it("strips existing queued attachment references when recovering an edit into the thread draft", () => { + const store = useComposerDraftStore.getState(); + const chip = formatInlineContextReference({ + kind: "image", + contextId: "image_queued-1", + label: "image.png", + }); + store.setPrompt(editTarget, `Check ${chip} closely`); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `Check ${chip}`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Check closely"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + + store.clearComposerContent(threadTarget); + store.setPrompt(editTarget, chip); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `${chip} note`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("discarded"); + expect(store.getComposerDraft(threadTarget)).toBeNull(); + }); + + it("matches a removed queued attachment for same-environment paste while rejecting other environments or payloads", () => { + const fileId = ChatAttachmentId.make("server-file-1"); + const contextId = ComposerContextId.make("file_local-1"); + const removedAttachment = { + type: "file" as const, + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const record = { + version: 1 as const, + kind: "file" as const, + contextId, + label: "notes.txt", + attachmentId: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toEqual({ attachment: removedAttachment, contextId }); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: EnvironmentId.make("other-environment"), + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record: { ...record, attachmentId: ChatAttachmentId.make("different-file") }, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + }); + it("does not overwrite a separate draft when the queued run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(threadTarget, "Separate draft"); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index e6b59e3a96b8..ca58777dcb44 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -1,5 +1,14 @@ import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; -import type { ChatAttachment, ResponseContextRecord } from "@t3tools/contracts"; +import type { + ChatAttachment, + ChatFileAttachment, + ChatImageAttachment, + ComposerContextId, + ComposerContextRecord, + EnvironmentId, + OrchestrationMessageContext, + ResponseContextRecord, +} from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import { composerDraftHasUserContent, @@ -11,6 +20,68 @@ import { import { msg } from "gt-react"; import { m } from "../../i18n/messages"; import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue"; +import { + attachmentContextRecord, + isSameComposerContextPayload, +} from "../../lib/composerContextRecords"; +import { removeInlineContextReference } from "../../lib/composerContextReferences"; + +export function isQueuedImageAttachment( + attachment: ChatAttachment, +): attachment is ChatImageAttachment { + return attachment.type === "image"; +} + +export function isQueuedFileAttachment( + attachment: ChatAttachment, +): attachment is ChatFileAttachment { + return attachment.type === "file"; +} + +export function attachmentContextIdsForRecord( + context: OrchestrationMessageContext | undefined, + attachment: Pick, +): ComposerContextId[] { + return (context?.records ?? []).flatMap((record) => + record.kind === attachment.type && + "attachmentId" in record && + record.attachmentId === attachment.id + ? [record.contextId] + : [], + ); +} + +export function matchRestorableQueuedAttachment(input: { + readonly environmentId: EnvironmentId; + readonly sourceEnvironmentId: EnvironmentId | null; + readonly record: Extract; + readonly removedQueuedAttachments: ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; + }>; +}): { readonly attachment: ChatAttachment; readonly contextId: ComposerContextId } | null { + if (input.sourceEnvironmentId !== input.environmentId) return null; + const match = input.removedQueuedAttachments.find( + ({ attachment, contextIds }) => + (isQueuedImageAttachment(attachment) || isQueuedFileAttachment(attachment)) && + attachment.type === input.record.kind && + contextIds.some((contextId) => + isSameComposerContextPayload( + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + input.record, + ), + ), + ); + if (!match || match.contextIds.length === 0) return null; + const contextId = + match.contextIds.find((candidate) => candidate === input.record.contextId) ?? + match.contextIds[0]!; + return { attachment: match.attachment, contextId }; +} /** Staged attachments upload as soon as they are added, so a dropped edit must release them. */ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { @@ -31,9 +102,21 @@ export function recoverQueuedMessageEdit(input: { readonly originalText: string; readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; + readonly existingAttachmentContextIds?: ReadonlyArray; }): "kept" | "discarded" | "clean" { const store = useComposerDraftStore.getState(); const draft = store.getComposerDraft(input.editTarget); + const strippedPrompt = + draft && (input.existingAttachmentContextIds?.length ?? 0) > 0 + ? input.existingAttachmentContextIds!.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + draft.prompt, + ) + : draft?.prompt; + const recoveredDraft = + draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt + ? { ...draft, prompt: strippedPrompt } + : draft; const recovery = resolveQueuedEditExit({ editChanged: input.removedExistingAttachment === true || @@ -42,10 +125,13 @@ export function recoverQueuedMessageEdit(input: { (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)), // A cleared edit has nothing to put back, so it can only be discarded. threadDraftEmpty: - composerDraftHasUserContent(draft) && + composerDraftHasUserContent(recoveredDraft) && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)), }); if (recovery === "kept") { + if (draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt) { + store.setPrompt(input.editTarget, strippedPrompt); + } store.moveComposerContent(input.editTarget, input.threadTarget); store.clearComposerContent(input.editTarget); } else { diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 61d0abd7319a..458f39dc9863 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type { RefObject } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { + type ChatAttachment, type ComposerContextClipboardFragment, type ComposerContextRecord, type EnvironmentId, @@ -59,6 +60,8 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; import { useStableCallback } from "../../hooks/useStableCallback"; import { countPreparingComposerImages } from "./preparingComposerImages"; +import type { QueuedAttachmentContextBinding } from "./composerContextUndo"; +import { matchRestorableQueuedAttachment } from "./queuedMessageEdit"; const isUnreachable = Schema.is( Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]), @@ -94,6 +97,8 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + readonly removedQueuedAttachments?: ReadonlyArray | undefined; + readonly onRestoreQueuedAttachment?: ((attachment: ChatAttachment) => void) | undefined; }) { const { environmentId, @@ -112,6 +117,8 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments, + onRestoreQueuedAttachment, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -433,6 +440,19 @@ export function useComposerContextImport(input: { case "image": case "file": { if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (questionAttachmentTarget === null && !conflicts) { + const restored = matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId, + record, + removedQueuedAttachments: removedQueuedAttachments ?? [], + }); + if (restored) { + onRestoreQueuedAttachment?.(restored.attachment); + rewritten.set(record.contextId, restored.contextId); + break; + } + } if (sourceEnvironmentId === null && !conflicts) { rewritten.set(record.contextId, record.contextId); break; diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16..5ad406da5ef9 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -2,6 +2,7 @@ import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, ChatAttachmentId, + ComposerContextId, MessageId, RunId, ThreadId, @@ -363,22 +364,83 @@ describe("useQueuedRunEdit", () => { expect(draft?.environmentContexts).toEqual([machine]); }); - it("saves only the thread mentions still in the edited message", async () => { + it("saves only the thread mentions and attachments still in the edited message", async () => { const { hook } = setup(); mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); const kept = threadContextRecord(THREAD_B, "Kept"); const removed = threadContextRecord(THREAD_A, "Removed"); + const removedImageId = ChatAttachmentId.make("server-image-removed"); + const keptFileId = ChatAttachmentId.make("server-file-kept"); + const removedImageContextId = ComposerContextId.make("image_local-removed"); + const keptFileContextId = ComposerContextId.make("file_local-kept"); + const removedImage = { + type: "image" as const, + id: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFile = { + type: "file" as const, + id: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const removedImageRecord = { + version: 1 as const, + kind: "image" as const, + contextId: removedImageContextId, + label: "image.png", + attachmentId: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFileRecord = { + version: 1 as const, + kind: "file" as const, + contextId: keptFileContextId, + label: "legacy.pdf", + attachmentId: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; const messageId = MessageId.make("message-1"); - const text = [kept, removed] - .map((record) => formatInlineContextReference(threadContextReference(record))) - .join(" and "); - const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }]; + const text = [ + formatInlineContextReference(threadContextReference(kept)), + formatInlineContextReference(threadContextReference(removed)), + formatInlineContextReference({ + kind: "image", + contextId: removedImageContextId, + label: "image.png", + }), + ].join(" and "); + const messages = [ + { + id: messageId, + text, + context: { version: 1, records: [kept, removed, removedImageRecord, keptFileRecord] }, + }, + ]; await using _screen = await render(view(THREAD_A, "queued", hook, messages)); - await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + await act(() => + requireHook(hook).beginEdit({ + runId: RUN, + messageId, + text, + attachments: [removedImage, keptFile], + }), + ); const target = requireHook(hook).draftTarget; - await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); + await act(() => { + useComposerDraftStore.getState().setThreadContexts(target, [kept]); + requireHook(hook).removeEditingAttachment(removedImageId); + }); const draft = useComposerDraftStore.getState().getComposerDraft(target); + expect(draft?.prompt).not.toContain(removedImageContextId); await requireHook(hook).saveEdit( { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, () => {}, @@ -387,7 +449,11 @@ describe("useQueuedRunEdit", () => { expect(mocks.editQueuedRun).toHaveBeenCalledWith( expect.objectContaining({ input: expect.objectContaining({ - edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), + text: draft?.prompt, + edit: expect.objectContaining({ + attachments: [keptFile], + context: { version: 1, records: [keptFileRecord, kept] }, + }), }), }), ); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 77989f8aebc0..a33fd9177635 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -69,6 +69,7 @@ import type { ChatComposerHandle } from "./ChatComposer"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { composerDraftContentChanged } from "./composerSend.logic"; import { + attachmentContextIdsForRecord, discardQueuedEditDraft, prepareQueuedEditAttachments, recoverQueuedMessageEdit, @@ -80,10 +81,9 @@ interface EditingQueuedRun { readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; + readonly originalAttachments: ReadonlyArray; readonly existingAttachments: ReadonlyArray; readonly context?: OrchestrationMessageContext | undefined; - /** Removing a server attachment changes the message even when the draft looks untouched. */ - readonly removedExistingAttachment?: true; } // Keyed by the route thread, so an edit survives navigating away and back. @@ -238,13 +238,34 @@ export function useQueuedRunEdit(input: { const urlByAttachmentId = new Map( imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]), ); + const originalReferencedContextIds = + editing === null ? null : new Set(collectInlineContextIds(editing.originalText)); + const attachmentContextIds = (attachment: ChatAttachment) => + editing === null + ? [] + : attachmentContextIdsForRecord(editing.context, attachment).filter((contextId) => + originalReferencedContextIds!.has(contextId), + ); const editingAttachments = editing === null ? null : editing.existingAttachments.map((attachment) => ({ attachment, url: urlByAttachmentId.get(attachment.id) ?? null, + contextIds: attachmentContextIds(attachment), })); + const existingAttachmentIds = new Set( + (editing?.existingAttachments ?? []).map((attachment) => attachment.id), + ); + const removedEditingAttachments = + editing === null + ? [] + : editing.originalAttachments + .filter((attachment) => !existingAttachmentIds.has(attachment.id)) + .map((attachment) => ({ + attachment, + contextIds: attachmentContextIds(attachment), + })); const focusComposerSoon = () => { window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); @@ -290,6 +311,7 @@ export function useQueuedRunEdit(input: { runId: request.runId, messageId: request.messageId, originalText: text, + originalAttachments: request.attachments, existingAttachments: request.attachments, context, }, @@ -313,7 +335,13 @@ export function useQueuedRunEdit(input: { threadTarget: threadDraftTarget, originalText: edit.originalText, originalReplyTo: reply ?? null, - removedExistingAttachment: edit.removedExistingAttachment === true, + removedExistingAttachment: + edit.existingAttachments.length < edit.originalAttachments.length, + existingAttachmentContextIds: (edit.context?.records ?? []).flatMap((record) => + (record.kind === "image" || record.kind === "file") && "attachmentId" in record + ? [record.contextId] + : [], + ), }); if (recovery === "clean") return; const title = appAtomRegistry.get( @@ -345,13 +373,39 @@ export function useQueuedRunEdit(input: { focusComposerSoon(); }); const removeEditingAttachment = useStableCallback((attachmentId: string) => { + const removed = editing?.existingAttachments.find( + (attachment) => attachment.id === attachmentId, + ); + const contextIds = removed ? attachmentContextIdsForRecord(editing?.context, removed) : []; queuedRunEdits.update(editKey, (current) => ({ ...current, - removedExistingAttachment: true, existingAttachments: current.existingAttachments.filter( (attachment) => attachment.id !== attachmentId, ), })); + if (editing !== null && contextIds.length > 0) { + const target = queuedRunEditDraftId(routeThreadRef, editing.runId); + const store = useComposerDraftStore.getState(); + const currentPrompt = store.getComposerDraft(target)?.prompt ?? ""; + const nextPrompt = contextIds.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + currentPrompt, + ); + if (nextPrompt !== currentPrompt) store.setPrompt(target, nextPrompt); + } + }); + const restoreEditingAttachment = useStableCallback((attachment: ChatAttachment) => { + queuedRunEdits.update(editKey, (current) => { + const keptIds = new Set([ + ...current.existingAttachments.map((entry) => entry.id), + attachment.id, + ]); + // Filtering the originals keeps the restored attachment in its original position. + return { + ...current, + existingAttachments: current.originalAttachments.filter((entry) => keptIds.has(entry.id)), + }; + }); }); // The same move as the queued row's "Send now" while a turn runs. @@ -478,9 +532,11 @@ export function useQueuedRunEdit(input: { isSaving, draftTarget, editingAttachments, + removedEditingAttachments, beginEdit, cancelEdit, removeEditingAttachment, + restoreEditingAttachment, saveEdit, }; } diff --git a/apps/web/src/components/composerContextPresentation.test.ts b/apps/web/src/components/composerContextPresentation.test.ts index 77b0a5fb7815..641e190ef86a 100644 --- a/apps/web/src/components/composerContextPresentation.test.ts +++ b/apps/web/src/components/composerContextPresentation.test.ts @@ -1,8 +1,16 @@ -import { ThreadId } from "@t3tools/contracts"; +import { ChatAttachmentId, ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { buildMessageContext } from "~/lib/composerContextRecords"; -import { composerContextRecordsFromDraft } from "./composerContextPresentation"; +import { composerFileNeedsReattach } from "~/composerDraftStore"; +import { + attachmentContextRecord, + buildMessageContext, + isSameComposerContextPayload, +} from "~/lib/composerContextRecords"; +import { + composerContextRecordsFromDraft, + uploadedContextRecordFromDraft, +} from "./composerContextPresentation"; describe("composerContextRecordsFromDraft", () => { it("resolves each wire reference to its own backing draft even when producer ids collide", () => { @@ -53,4 +61,88 @@ describe("composerContextRecordsFromDraft", () => { expect(draftRecords.get(record.contextId)?.kind).toBe(record.kind); } }); + + it("resolves existing queued attachments under their original wire context ids", () => { + const environmentId = EnvironmentId.make("env-1"); + const imageContextId = ComposerContextId.make("image_local-shot"); + const fileContextId = ComposerContextId.make("file_local-notes"); + const imageId = ChatAttachmentId.make("server-shot"); + const fileId = ChatAttachmentId.make("server-notes"); + const source = { + kind: "snap-shot" as const, + capturedAt: "2026-11-22T14:00:00.000Z", + appName: "Safari", + windowTitle: "Example", + }; + const imageAttachment = { + type: "image" as const, + id: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + source, + }; + const draftRecords = composerContextRecordsFromDraft({ + terminalContexts: [], + environmentId, + existingAttachments: [ + { + attachment: imageAttachment, + url: "http://127.0.0.1/assets/server-shot", + contextIds: [imageContextId], + }, + { + attachment: { + type: "file", + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + url: null, + contextIds: [fileContextId], + }, + ], + }); + + const imageEntry = draftRecords.get(imageContextId); + expect(imageEntry).toMatchObject({ + kind: "image", + record: { + id: imageId, + name: "image.png", + previewUrl: "http://127.0.0.1/assets/server-shot", + source, + }, + }); + const uploadedImageRecord = uploadedContextRecordFromDraft(imageEntry!); + expect(uploadedImageRecord).toMatchObject({ + kind: "image", + contextId: imageContextId, + attachmentId: imageId, + source, + }); + expect( + isSameComposerContextPayload( + uploadedImageRecord!, + attachmentContextRecord({ + attachment: imageAttachment, + attachmentId: imageId, + contextId: imageContextId, + }), + ), + ).toBe(true); + + const fileEntry = draftRecords.get(fileContextId); + expect(fileEntry?.kind).toBe("file"); + if (fileEntry?.kind === "file") { + expect(composerFileNeedsReattach(fileEntry.record)).toBe(false); + expect(fileEntry.record.uploadEnvironmentId).toBe(environmentId); + } + expect(uploadedContextRecordFromDraft(fileEntry!)).toMatchObject({ + kind: "file", + contextId: fileContextId, + attachmentId: fileId, + }); + }); }); diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index ab7ce9b40186..0fb3f31e5413 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -2,7 +2,10 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, + EnvironmentId, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; @@ -40,6 +43,7 @@ import { } from "~/lib/composerContextRecords"; import type { TerminalContextDraft } from "~/lib/terminalContext"; import type { ReviewCommentContext } from "~/reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./chat/queuedMessageEdit"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; import { EnvironmentContextChip } from "./EnvironmentContextChip"; import { ThreadContextChip } from "./ThreadContextChip"; @@ -60,6 +64,11 @@ import { UnresolvedChip, } from "./contextChipParts"; +export interface ComposerImageContextAttachment extends Omit { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; +} + export type ComposerDraftContextRecord = | { kind: "terminal"; record: TerminalContextDraft } | { kind: "review-comment"; record: ReviewCommentContext } @@ -68,8 +77,18 @@ export type ComposerDraftContextRecord = record: PreviewAnnotationPayload; screenshot?: ComposerImageAttachment | undefined; } - | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined } - | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined } + | { + kind: "image"; + record: ComposerImageContextAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } + | { + kind: "file"; + record: ComposerFileAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } | { kind: "thread"; record: ThreadContextRecord } | { kind: "environment"; record: EnvironmentContextRecord }; @@ -84,7 +103,7 @@ export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new M export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) { if (entry.kind !== "image" && entry.kind !== "file") return null; - return uploadedAttachmentContextRecord(entry.record, entry.upload); + return uploadedAttachmentContextRecord(entry.record, entry.upload, entry.contextId); } export const ComposerContextRecordsContext = createContext( @@ -99,9 +118,44 @@ export function composerContextRecordsFromDraft(input: { environmentContexts?: ReadonlyArray; images?: ReadonlyArray; files?: ReadonlyArray; + existingAttachments?: + | ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; + }> + | undefined; + environmentId?: EnvironmentId | undefined; uploadsByImageId?: Readonly>; }): ComposerDraftContextRecords { const records = new Map(); + for (const entry of input.existingAttachments ?? []) { + for (const contextId of entry.contextIds ?? []) { + if (isQueuedImageAttachment(entry.attachment)) { + records.set(contextId, { + kind: "image", + contextId, + record: { + ...entry.attachment, + previewUrl: entry.url ?? "", + file: null, + uploadedAttachmentId: entry.attachment.id, + }, + }); + } else if (isQueuedFileAttachment(entry.attachment)) { + records.set(contextId, { + kind: "file", + contextId, + record: { + ...entry.attachment, + file: null, + uploadedAttachmentId: entry.attachment.id, + ...(input.environmentId ? { uploadEnvironmentId: input.environmentId } : {}), + }, + }); + } + } + } for (const record of input.images ?? []) { records.set(imageContextReference(record).contextId, { kind: "image", @@ -183,7 +237,7 @@ function useUploadStatusSuffix( } function attachmentTooltip( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: Pick, upload: AttachmentUploadState | undefined, resolve: MessageResolver, ): string { @@ -193,7 +247,7 @@ function attachmentTooltip( } function ImageContextChip(props: { - record: ComposerImageAttachment; + record: ComposerImageContextAttachment; upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 31b7239719f1..6f1c9d3bb822 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -9,6 +9,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -488,39 +490,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: {