diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 48457d2171..ddf49e163a 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -10,7 +10,9 @@ import { import { describe, expect, it } from "vite-plus/test"; import type { Thread } from "../types"; +import type { ComposerAttachment } from "../composerDraftStore"; import { + buildTurnUploadAttachment, MAX_HIDDEN_MOUNTED_PREVIEW_THREADS, MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, branchMismatchKey, @@ -725,3 +727,48 @@ describe("deriveLockedProvider", () => { ).toBe("codex"); }); }); + +describe("buildTurnUploadAttachment", () => { + const readDataUrl = (file: File) => Promise.resolve(`data:${file.type};base64,AAAA`); + + function makeComposerAttachment(input: { + type: "image" | "file"; + name: string; + mimeType: string; + }): ComposerAttachment { + const file = new File([new Uint8Array(4)], input.name, { type: input.mimeType }); + return { + type: input.type, + id: `att-${input.name}`, + name: input.name, + mimeType: input.mimeType, + sizeBytes: file.size, + previewUrl: `blob:${input.name}`, + file, + } as ComposerAttachment; + } + + it("sends a non-image attachment as the file upload variant", async () => { + await expect( + buildTurnUploadAttachment( + makeComposerAttachment({ type: "file", name: "spec.pdf", mimeType: "application/pdf" }), + readDataUrl, + ), + ).resolves.toEqual({ + type: "file", + name: "spec.pdf", + mimeType: "application/pdf", + sizeBytes: 4, + dataUrl: "data:application/pdf;base64,AAAA", + }); + }); + + it("leaves images on the image upload variant", async () => { + await expect( + buildTurnUploadAttachment( + makeComposerAttachment({ type: "image", name: "shot.png", mimeType: "image/png" }), + readDataUrl, + ), + ).resolves.toMatchObject({ type: "image", mimeType: "image/png" }); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 71d61468ff..b7bcb4c1c7 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -11,7 +11,7 @@ import { type TurnId, } from "@t3tools/contracts"; import { type ChatMessage, type SessionPhase, type Thread } from "../types"; -import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; +import { type ComposerAttachment, type DraftThreadState } from "../composerDraftStore"; import * as Schema from "effect/Schema"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentThreadDetails } from "../state/threads"; @@ -179,12 +179,24 @@ export function revokeBlobPreviewUrl(previewUrl: string | undefined): void { URL.revokeObjectURL(previewUrl); } -export function revokeUserMessagePreviewUrls(message: ChatMessage): void { +/** + * Releases the blob previews an optimistic user message is holding. + * + * Every attachment variant gets a blob URL at intake, so the release is + * variant-agnostic. `retainedPreviewUrls` skips the image previews that were + * handed off to cross-fade against the server's signed URL — file cards have + * no such cross-fade, so their blobs are always released here. + */ +export function revokeUserMessagePreviewUrls( + message: ChatMessage, + retainedPreviewUrls?: ReadonlyArray, +): void { if (message.role !== "user" || !message.attachments) { return; } + const retained = retainedPreviewUrls ? new Set(retainedPreviewUrls) : null; for (const attachment of message.attachments) { - if (attachment.type !== "image") { + if (attachment.previewUrl && retained?.has(attachment.previewUrl)) { continue; } revokeBlobPreviewUrl(attachment.previewUrl); @@ -226,6 +238,32 @@ export function readFileAsDataUrl(file: File): Promise { }); } +/** + * Upload shape for one composer attachment on `thread.turn.start`. + * + * The variant tag rides along unchanged: images stay `type: "image"` (mime + * constrained to `image/*` by the contract), and everything staged on a + * Hermes thread goes as `type: "file"` with its own mime. + */ +export async function buildTurnUploadAttachment( + attachment: ComposerAttachment, + readDataUrl: (file: File) => Promise, +): Promise<{ + type: "image" | "file"; + name: string; + mimeType: string; + sizeBytes: number; + dataUrl: string; +}> { + return { + type: attachment.type, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + dataUrl: await readDataUrl(attachment.file), + }; +} + export function resolveSendEnvMode(input: { requestedEnvMode: DraftThreadEnvMode; isGitRepo: boolean; @@ -233,9 +271,7 @@ export function resolveSendEnvMode(input: { return input.isGitRepo ? input.requestedEnvMode : "local"; } -export function cloneComposerImageForRetry( - image: ComposerImageAttachment, -): ComposerImageAttachment { +export function cloneComposerImageForRetry(image: ComposerAttachment): ComposerAttachment { if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) { return image; } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9d38b644b3..25735f6ada 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -178,7 +178,7 @@ import { } from "../logicalProject"; import { buildDraftThreadRouteParams } from "../threadRoutes"; import { - type ComposerImageAttachment, + type ComposerAttachment, type DraftThreadEnvMode, useComposerDraftStore, type DraftId, @@ -266,6 +266,7 @@ import { PullRequestDialogState, cloneComposerImageForRetry, deriveLockedProvider, + buildTurnUploadAttachment, readFileAsDataUrl, reconcileMountedTerminalThreadIds, resolveThreadMetadataUpdateForNextTurn, @@ -305,6 +306,8 @@ import { useAssetUrls } from "../assets/assetUrls"; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; +const FILE_ONLY_BOOTSTRAP_PROMPT = + "[User attached one or more files without additional text. Respond using the conversation context and the attached file(s).]"; const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; @@ -1242,7 +1245,7 @@ function ChatViewContent(props: ChatViewProps) { (store) => store.setLogicalProjectDraftThreadId, ); const promptRef = useRef(""); - const composerImagesRef = useRef([]); + const composerImagesRef = useRef([]); const composerTerminalContextsRef = useRef([]); const composerElementContextsRef = useRef([]); const localComposerRef = useRef(null); @@ -3813,9 +3816,8 @@ function ChatViewContent(props: ChatViewProps) { const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage); if (previewUrls.length > 0) { handoffAttachmentPreviews(removedMessage.id, previewUrls); - continue; } - revokeUserMessagePreviewUrls(removedMessage); + revokeUserMessagePreviewUrls(removedMessage, previewUrls); } return () => { window.clearTimeout(timer); @@ -4635,19 +4637,17 @@ function ChatViewContent(props: ChatViewProps) { model: ctxSelectedModel, models: ctxSelectedProviderModels, effort: ctxSelectedPromptEffort, - text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT, + text: + messageTextForSend || + (composerImagesSnapshot.some((attachment) => attachment.type === "file") + ? FILE_ONLY_BOOTSTRAP_PROMPT + : IMAGE_ONLY_BOOTSTRAP_PROMPT), }); const turnAttachmentsPromise = Promise.all( - composerImagesSnapshot.map(async (image) => ({ - type: "image" as const, - name: image.name, - mimeType: image.mimeType, - sizeBytes: image.sizeBytes, - dataUrl: await readFileAsDataUrl(image.file), - })), + composerImagesSnapshot.map((image) => buildTurnUploadAttachment(image, readFileAsDataUrl)), ); const optimisticAttachments = composerImagesSnapshot.map((image) => ({ - type: "image" as const, + type: image.type, id: image.id, name: image.name, mimeType: image.mimeType, @@ -4699,17 +4699,11 @@ function ChatViewContent(props: ChatViewProps) { clearComposerDraftContent(composerDraftTarget); composerRef.current?.resetCursorState(); - let firstComposerImageName: string | null = null; - if (composerImagesSnapshot.length > 0) { - const firstComposerImage = composerImagesSnapshot[0]; - if (firstComposerImage) { - firstComposerImageName = firstComposerImage.name; - } - } + const firstComposerAttachment = composerImagesSnapshot[0] ?? null; let titleSeed = trimmed; if (!titleSeed) { - if (firstComposerImageName) { - titleSeed = `Image: ${firstComposerImageName}`; + if (firstComposerAttachment) { + titleSeed = `${firstComposerAttachment.type === "image" ? "Image" : "File"}: ${firstComposerAttachment.name}`; } else if (composerTerminalContextsSnapshot.length > 0) { titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!); } else if (composerElementContextsSnapshot.length > 0) { diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 8fd8f4590c..34cfd671da 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -16,7 +16,6 @@ import { ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, - PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, } from "@t3tools/contracts"; import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; @@ -50,7 +49,7 @@ import { makeComposerMentionDragHandlers, } from "./composerMentionDrag"; import { - type ComposerImageAttachment, + type ComposerAttachment, type DraftId, type PersistedComposerImageAttachment, hydrateImagesFromPersisted, @@ -58,6 +57,11 @@ import { useComposerThreadDraft, useEffectiveComposerModelState, } from "../../composerDraftStore"; +import { + formatComposerAttachmentSize, + isComposerImageMimeType, + planComposerAttachmentIntake, +} from "../../lib/composerAttachments"; import { EMPTY_PROMPT_STASH_QUEUE, MAX_STASH_ENTRIES_PER_QUEUE, @@ -68,7 +72,7 @@ import { } from "../../promptStashStore"; import { ComposerStashBadge } from "./ComposerStashBadge"; import { ComposerStashMenu } from "./ComposerStashMenu"; -import { compressImageForStash } from "../../lib/stashImageCompression"; +import { compressImageForStash, readAttachmentForStash } from "../../lib/stashImageCompression"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { getTerminalFocusOwner } from "../../lib/terminalFocus"; import { resolveShortcutCommand } from "../../keybindings"; @@ -178,7 +182,9 @@ import { toastManager } from "../ui/toast"; import { BotIcon, CircleAlertIcon, + FileIcon, ListTodoIcon, + PaperclipIcon, PencilRulerIcon, type LucideIcon, LockIcon, @@ -218,8 +224,6 @@ import { searchProviderSkills } from "../../providerSkillSearch"; import { useMediaQuery } from "../../hooks/useMediaQuery"; import type { ReviewCommentContext } from "../../reviewCommentContext"; -const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; - const runtimeModeConfig: Record< RuntimeMode, { label: string; description: string; icon: LucideIcon } @@ -305,6 +309,12 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop * agent to open (every workspace provider). */ onOpenAgent: (() => void) | null; + /** + * Opens the file picker. Null off Hermes — every other provider's composer + * takes images through drag/paste only, and a picker there would offer an + * intake path the rest of the pipeline rejects. + */ + onAttachFiles: (() => void) | null; interactionMode: ProviderInteractionMode; runtimeMode: RuntimeMode; showPlanToggle: boolean; @@ -410,6 +420,31 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop ) : null; + // Hermes-only: the picker exists because that composer takes any file type, + // and drag/paste are not reachable at all on touch. + const attachButton = props.onAttachFiles ? ( + <> + + + + } + > + + + Attach files + + + ) : null; + const agentButton = props.onOpenAgent ? ( <> @@ -443,6 +478,8 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop {interactionModeToggle} + {attachButton} + {agentButton} {props.showPlanToggle ? ( @@ -564,7 +601,7 @@ export interface ChatComposerHandle { /** Get the current prompt/effort/model state for use in send. */ getSendContext: () => { prompt: string; - images: ComposerImageAttachment[]; + images: ComposerAttachment[]; terminalContexts: TerminalContextDraft[]; elementContexts: ElementContextDraft[]; previewAnnotations: PreviewAnnotationPayload[]; @@ -656,7 +693,7 @@ export interface ChatComposerProps { // Refs the parent needs kept in sync promptRef: React.RefObject; - composerImagesRef: React.RefObject; + composerImagesRef: React.RefObject; composerTerminalContextsRef: React.RefObject; composerElementContextsRef: React.RefObject; composerRef: React.RefObject; @@ -780,6 +817,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerPreviewAnnotations = composerDraft.previewAnnotations; const composerReviewComments = composerDraft.reviewComments; const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds; + // The zoom dialog and the annotation cards are image-only; file attachments + // share the pending strip but have nothing to preview. + const composerPreviewableImages = useMemo( + () => composerImages.filter((image) => image.type === "image"), + [composerImages], + ); const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); const addComposerDraftImage = useComposerDraftStore((store) => store.addImage); @@ -925,6 +968,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const selectedProvider: ProviderDriverKind = selectedProviderEntry?.driverKind ?? requestedDriverKind; const allowHermesSteering = phase === "running" && selectedProvider === "hermes"; + // Non-image attachments are Hermes-only: it is the one driver whose + // transport carries arbitrary files to the agent. Every other provider + // keeps the image-only intake it has always had. + const allowsFileAttachments = selectedProvider === "hermes"; // A Home thread is permanently bound to one instance and one model slug — // `thread.create` fixes both, and Hermes sets @@ -1082,6 +1129,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) // ------------------------------------------------------------------ const composerEditorRef = useRef(null); const composerFormRef = useRef(null); + const composerFileInputRef = useRef(null); const composerSurfaceRef = useRef(null); const composerSelectLockRef = useRef(false); const composerMenuOpenRef = useRef(false); @@ -1372,14 +1420,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); const addComposerImage = useCallback( - (image: ComposerImageAttachment) => { + (image: ComposerAttachment) => { addComposerDraftImage(composerDraftTarget, image); }, [composerDraftTarget, addComposerDraftImage], ); const addComposerImagesToDraft = useCallback( - (images: ComposerImageAttachment[]) => { + (images: ComposerAttachment[]) => { addComposerDraftImages(composerDraftTarget, images); }, [composerDraftTarget, addComposerDraftImages], @@ -2270,7 +2318,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const oversizedImageNames: string[] = []; const unreadableImageNames: string[] = []; for (const image of images) { - const result = await compressImageForStash(image.file); + // Only images can be re-encoded to fit the budget; a PDF or archive + // is stored verbatim when it fits and dropped when it does not. + const result = isComposerImageMimeType(image.mimeType) + ? await compressImageForStash(image.file) + : await readAttachmentForStash(image.file, image.mimeType); if (!result.ok) { // "too large" and "could not be read" are distinct outcomes; the // menu and restore toast report them separately. @@ -2400,38 +2452,29 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (pendingUserInputs.length > 0) { toastManager.add({ type: "error", - title: "Attach images after answering plan questions.", + title: allowsFileAttachments + ? "Attach files after answering plan questions." + : "Attach images after answering plan questions.", }); return; } - const nextImages: ComposerImageAttachment[] = []; - let nextImageCount = composerImagesRef.current.length; - let error: string | null = null; - for (const file of files) { - if (!file.type.startsWith("image/")) { - error = `Unsupported file type for '${file.name}'. Please attach image files only.`; - continue; - } - if (file.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - error = `'${file.name}' exceeds the ${IMAGE_SIZE_LIMIT_LABEL} attachment limit.`; - continue; - } - if (nextImageCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { - error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`; - break; - } - const previewUrl = URL.createObjectURL(file); - nextImages.push({ - type: "image", - id: randomUUID(), - name: file.name || "image", - mimeType: file.type, - sizeBytes: file.size, - previewUrl, - file, - }); - nextImageCount += 1; - } + const { accepted, error } = planComposerAttachmentIntake({ + files, + existingCount: composerImagesRef.current.length, + allowNonImageFiles: allowsFileAttachments, + }); + const nextImages: ComposerAttachment[] = accepted.map((entry) => ({ + type: entry.type, + id: randomUUID(), + name: entry.file.name || (entry.type === "image" ? "image" : "file"), + mimeType: entry.mimeType, + sizeBytes: entry.file.size, + // Blob URLs back both the image thumbnail and (for files) nothing + // visible, but the draft store keys dedupe/revocation off this field + // for every attachment, so it is always created. + previewUrl: URL.createObjectURL(entry.file), + file: entry.file, + })); if (nextImages.length === 1 && nextImages[0]) { addComposerImage(nextImages[0]); } else if (nextImages.length > 1) { @@ -2444,16 +2487,34 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) removeComposerImageFromDraft(imageId); }; + const openComposerFilePicker = () => { + composerFileInputRef.current?.click(); + }; + + const onComposerFileInputChange = (event: React.ChangeEvent) => { + const files = Array.from(event.target.files ?? []); + // Reset before the intake so picking the same file twice in a row still + // fires a change event. + event.target.value = ""; + if (files.length === 0) return; + addComposerImages(files); + focusComposer(); + }; + // ------------------------------------------------------------------ // Callbacks: paste / drag // ------------------------------------------------------------------ const onComposerPaste = (event: React.ClipboardEvent) => { const files = Array.from(event.clipboardData.files); if (files.length === 0) return; - const imageFiles = files.filter((file) => file.type.startsWith("image/")); - if (imageFiles.length === 0) return; + // Non-image pastes stay untouched off Hermes so a copied file still + // falls through to the editor's own paste handling there. + const pastedFiles = allowsFileAttachments + ? files + : files.filter((file) => file.type.startsWith("image/")); + if (pastedFiles.length === 0) return; event.preventDefault(); - addComposerImages(imageFiles); + addComposerImages(pastedFiles); }; const onComposerDragEnter = (event: React.DragEvent) => { @@ -2731,6 +2792,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="mx-auto w-full min-w-0 max-w-3xl" data-chat-composer-form="true" > + {/* Only mounted on Hermes threads, so no other provider's composer can + route a picked file into the image-only intake. */} + {allowsFileAttachments ? ( + + ) : null}
0 && ( removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId) } onExpandImage={(imageId) => { - const preview = buildExpandedImagePreview(composerImages, imageId); + const preview = buildExpandedImagePreview(composerPreviewableImages, imageId); if (preview) onExpandImage(preview); }} className="mb-3" @@ -3059,66 +3133,120 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (annotation) => annotation.id === image.id, ), ) - .map((image) => ( -
- {image.previewUrl ? ( - - ) : ( -
- {image.name} -
- )} - {nonPersistedComposerImageIdSet.has(image.id) && ( - - - - - } - /> - - Draft attachment could not be saved locally and may be lost on - navigation. - - - )} - -
- ))} +
+ ) : ( +
+ {image.previewUrl ? ( + + ) : ( +
+ {image.name} +
+ )} + {nonPersistedComposerImageIdSet.has(image.id) && ( + + + + + } + /> + + Draft attachment could not be saved locally and may be lost on + navigation. + + + )} + +
+ ), + )} )} @@ -3263,6 +3391,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showInteractionModeToggle={composerProviderControls.showInteractionModeToggle} showRuntimeModeSelector={composerProviderControls.showRuntimeModeSelector} onOpenAgent={openAgentPage} + onAttachFiles={allowsFileAttachments ? openComposerFilePicker : null} traitsMenuContent={providerTraitsMenuContent} onToggleInteractionMode={toggleInteractionMode} onTogglePlanSidebar={togglePlanSidebar} @@ -3280,6 +3409,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showInteractionModeToggle={composerProviderControls.showInteractionModeToggle} showRuntimeModeSelector={composerProviderControls.showRuntimeModeSelector} onOpenAgent={openAgentPage} + onAttachFiles={allowsFileAttachments ? openComposerFilePicker : null} interactionMode={interactionMode} runtimeMode={runtimeMode} showPlanToggle={showPlanSidebarToggle} diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx index 19ba68e9ff..15f638387b 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx @@ -1,6 +1,6 @@ import { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts"; import { memo, type ReactNode } from "react"; -import { EllipsisIcon, ListTodoIcon } from "lucide-react"; +import { EllipsisIcon, ListTodoIcon, PaperclipIcon } from "lucide-react"; import { Button } from "../ui/button"; import { HermesIcon } from "../HermesIcon"; import { @@ -30,6 +30,11 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls * has no agent page to open. */ onOpenAgent: (() => void) | null; + /** + * Mirrors the wide-layout paperclip. Null when this composer's provider + * takes images through drag/paste only (everything but Hermes). + */ + onAttachFiles: (() => void) | null; traitsMenuContent?: ReactNode; onToggleInteractionMode: () => void; onTogglePlanSidebar: () => void; @@ -91,6 +96,15 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls ) : null} + {props.onAttachFiles ? ( + <> + + + + Attach files + + + ) : null} {props.onOpenAgent ? ( <> diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index bc1b710730..4ccf8bb3ca 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -65,7 +65,9 @@ import { markPromotedDraftThreadByRef, markPromotedDraftThreads, markPromotedDraftThreadsByRef, + type ComposerFileAttachment, type ComposerImageAttachment, + hydrateImagesFromPersisted, useComposerDraftStore, DraftId, } from "./composerDraftStore"; @@ -104,6 +106,27 @@ function makeImage(input: { }; } +function makeFileAttachment(input: { + id: string; + previewUrl: string; + name?: string; + mimeType?: string; + sizeBytes?: number; +}): ComposerFileAttachment { + const name = input.name ?? "spec.pdf"; + const mimeType = input.mimeType ?? "application/pdf"; + const file = new File([new Uint8Array(input.sizeBytes ?? 6)], name, { type: mimeType }); + return { + type: "file", + id: input.id, + name, + mimeType, + sizeBytes: file.size, + previewUrl: input.previewUrl, + file, + }; +} + function makeTerminalContext(input: { id: string; text?: string; @@ -289,6 +312,70 @@ describe("composerDraftStore clearComposerContent", () => { }); }); +describe("composerDraftStore file attachments", () => { + const threadId = ThreadId.make("thread-files"); + const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); + let originalRevokeObjectUrl: typeof URL.revokeObjectURL; + let revokeSpy: ReturnType void>>; + + beforeEach(() => { + resetComposerDraftStore(); + originalRevokeObjectUrl = URL.revokeObjectURL; + revokeSpy = vi.fn(); + URL.revokeObjectURL = revokeSpy; + }); + + afterEach(() => { + URL.revokeObjectURL = originalRevokeObjectUrl; + }); + + it("holds non-image attachments in the same list as images", () => { + const image = makeImage({ id: "img-1", previewUrl: "blob:image" }); + const pdf = makeFileAttachment({ id: "file-1", previewUrl: "blob:pdf" }); + + useComposerDraftStore.getState().addImages(threadRef, [image, pdf]); + + const draft = draftFor(threadId, TEST_ENVIRONMENT_ID); + expect(draft?.images.map((attachment) => [attachment.id, attachment.type])).toEqual([ + ["img-1", "image"], + ["file-1", "file"], + ]); + }); + + it("removes a file attachment and revokes its preview URL", () => { + const pdf = makeFileAttachment({ id: "file-1", previewUrl: "blob:pdf" }); + useComposerDraftStore.getState().addImage(threadRef, pdf); + + useComposerDraftStore.getState().removeImage(threadRef, "file-1"); + + expect(draftFor(threadId, TEST_ENVIRONMENT_ID)).toBeUndefined(); + expect(revokeSpy).toHaveBeenCalledWith("blob:pdf"); + }); + + it("re-derives the file variant when hydrating a persisted draft", () => { + const [image, file] = hydrateImagesFromPersisted([ + { + id: "img-1", + name: "shot.png", + mimeType: "image/png", + sizeBytes: 4, + dataUrl: "data:image/png;base64,AAAA", + }, + { + id: "file-1", + name: "spec.pdf", + mimeType: "application/pdf", + sizeBytes: 4, + dataUrl: "data:application/pdf;base64,AAAA", + }, + ]); + + expect(image?.type).toBe("image"); + expect(file?.type).toBe("file"); + expect(file?.name).toBe("spec.pdf"); + }); +}); + describe("composerDraftStore syncPersistedAttachments", () => { const threadId = ThreadId.make("thread-sync-persisted"); const threadRef = scopeThreadRef(TEST_ENVIRONMENT_ID, threadId); diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 16c99abad8..39a24592a4 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -33,7 +33,13 @@ import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model" import { useMemo } from "react"; import { getLocalStorageItem } from "./hooks/useLocalStorage"; import { resolveAppModelSelection, resolveAppModelSelectionForInstance } from "./modelSelection"; -import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types"; +import { + DEFAULT_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + type ChatFileAttachment, + type ChatImageAttachment, +} from "./types"; +import { isComposerImageMimeType } from "./lib/composerAttachments"; import { type TerminalContextDraft, ensureInlineTerminalContextPlaceholders, @@ -92,6 +98,19 @@ export interface ComposerImageAttachment extends Omit { + previewUrl: string; + file: File; +} + +export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment; + const PersistedTerminalContextDraft = Schema.Struct({ id: Schema.String, threadId: ThreadId, @@ -249,7 +268,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({ */ export interface ComposerThreadDraftState { prompt: string; - images: ComposerImageAttachment[]; + images: ComposerAttachment[]; nonPersistedImageIds: string[]; persistedAttachments: PersistedComposerImageAttachment[]; terminalContexts: TerminalContextDraft[]; @@ -443,8 +462,8 @@ interface ComposerDraftStoreState { threadRef: ComposerThreadTarget, interactionMode: ProviderInteractionMode | null | undefined, ) => void; - addImage: (threadRef: ComposerThreadTarget, image: ComposerImageAttachment) => void; - addImages: (threadRef: ComposerThreadTarget, images: ComposerImageAttachment[]) => void; + addImage: (threadRef: ComposerThreadTarget, image: ComposerAttachment) => void; + addImages: (threadRef: ComposerThreadTarget, images: ComposerAttachment[]) => void; removeImage: (threadRef: ComposerThreadTarget, imageId: string) => void; insertTerminalContext: ( threadRef: ComposerThreadTarget, @@ -567,7 +586,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze, -): ComposerImageAttachment[] { +): ComposerAttachment[] { return attachments.flatMap((attachment) => { const file = hydratePersistedComposerImageAttachment(attachment); if (!file) return []; + // The persisted shape carries no variant tag, so it is re-derived from + // the mime exactly as intake classifies it. Persisting the tag instead + // would need a storage migration for no behavioural gain. return [ { - type: "image" as const, + ...(isComposerImageMimeType(attachment.mimeType) + ? { type: "image" as const } + : { type: "file" as const }), id: attachment.id, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, previewUrl: attachment.dataUrl, file, - } satisfies ComposerImageAttachment, + } satisfies ComposerAttachment, ]; }); } @@ -2874,7 +2898,7 @@ const composerDraftStore = create()( existing.images.map((image) => composerImageDedupKey(image)), ); const acceptedPreviewUrls = new Set(existing.images.map((image) => image.previewUrl)); - const dedupedIncoming: ComposerImageAttachment[] = []; + const dedupedIncoming: ComposerAttachment[] = []; for (const image of images) { const dedupKey = composerImageDedupKey(image); if (existingIds.has(image.id) || existingDedupKeys.has(dedupKey)) { diff --git a/apps/web/src/lib/composerAttachments.test.ts b/apps/web/src/lib/composerAttachments.test.ts new file mode 100644 index 0000000000..da8822206a --- /dev/null +++ b/apps/web/src/lib/composerAttachments.test.ts @@ -0,0 +1,130 @@ +import { + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PROVIDER_SEND_TURN_MAX_FILE_BYTES, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + formatComposerAttachmentSize, + planComposerAttachmentIntake, + resolveComposerAttachmentMimeType, +} from "./composerAttachments"; + +function makeFile(input: { name: string; mimeType: string; sizeBytes?: number }): File { + const sizeBytes = input.sizeBytes ?? 8; + return new File([new Uint8Array(sizeBytes)], input.name, { type: input.mimeType }); +} + +/** Avoids allocating a real 11MB buffer just to exercise the size guard. */ +function makeOversizedFile(input: { name: string; mimeType: string; sizeBytes: number }): File { + const file = makeFile({ name: input.name, mimeType: input.mimeType }); + Object.defineProperty(file, "size", { value: input.sizeBytes }); + return file; +} + +describe("planComposerAttachmentIntake", () => { + it("accepts any file type when non-image files are allowed (Hermes)", () => { + const plan = planComposerAttachmentIntake({ + files: [ + makeFile({ name: "shot.png", mimeType: "image/png" }), + makeFile({ name: "spec.pdf", mimeType: "application/pdf" }), + ], + existingCount: 0, + allowNonImageFiles: true, + }); + + expect(plan.error).toBeNull(); + expect(plan.accepted.map((entry) => [entry.file.name, entry.type])).toEqual([ + ["shot.png", "image"], + ["spec.pdf", "file"], + ]); + }); + + it("rejects non-image files exactly as before when they are not allowed", () => { + const plan = planComposerAttachmentIntake({ + files: [ + makeFile({ name: "spec.pdf", mimeType: "application/pdf" }), + makeFile({ name: "shot.png", mimeType: "image/png" }), + ], + existingCount: 0, + allowNonImageFiles: false, + }); + + expect(plan.accepted.map((entry) => entry.file.name)).toEqual(["shot.png"]); + expect(plan.error).toBe( + "Unsupported file type for 'spec.pdf'. Please attach image files only.", + ); + }); + + it("rejects a file over the 10MB per-file limit with feedback", () => { + const plan = planComposerAttachmentIntake({ + files: [ + makeOversizedFile({ + name: "huge.pdf", + mimeType: "application/pdf", + sizeBytes: PROVIDER_SEND_TURN_MAX_FILE_BYTES + 1, + }), + ], + existingCount: 0, + allowNonImageFiles: true, + }); + + expect(plan.accepted).toEqual([]); + expect(plan.error).toBe("'huge.pdf' exceeds the 10MB attachment limit."); + }); + + it("keeps the existing image size limit for images", () => { + const plan = planComposerAttachmentIntake({ + files: [ + makeOversizedFile({ + name: "huge.png", + mimeType: "image/png", + sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, + }), + ], + existingCount: 0, + allowNonImageFiles: false, + }); + + expect(plan.accepted).toEqual([]); + expect(plan.error).toBe("'huge.png' exceeds the 10MB attachment limit."); + }); + + it("stops at the shared per-message attachment count", () => { + const plan = planComposerAttachmentIntake({ + files: [ + makeFile({ name: "a.pdf", mimeType: "application/pdf" }), + makeFile({ name: "b.pdf", mimeType: "application/pdf" }), + ], + existingCount: PROVIDER_SEND_TURN_MAX_ATTACHMENTS - 1, + allowNonImageFiles: true, + }); + + expect(plan.accepted.map((entry) => entry.file.name)).toEqual(["a.pdf"]); + expect(plan.error).toBe( + `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.`, + ); + }); +}); + +describe("resolveComposerAttachmentMimeType", () => { + it("falls back to the generic binary type for unrecognised extensions", () => { + expect(resolveComposerAttachmentMimeType(makeFile({ name: "data.bin", mimeType: "" }))).toBe( + "application/octet-stream", + ); + expect( + resolveComposerAttachmentMimeType( + makeFile({ name: "spec.pdf", mimeType: "application/pdf" }), + ), + ).toBe("application/pdf"); + }); +}); + +describe("formatComposerAttachmentSize", () => { + it("scales the unit to the size", () => { + expect(formatComposerAttachmentSize(512)).toBe("512 B"); + expect(formatComposerAttachmentSize(2048)).toBe("2 KB"); + expect(formatComposerAttachmentSize(3 * 1024 * 1024)).toBe("3.0 MB"); + }); +}); diff --git a/apps/web/src/lib/composerAttachments.ts b/apps/web/src/lib/composerAttachments.ts new file mode 100644 index 0000000000..f89dd493e7 --- /dev/null +++ b/apps/web/src/lib/composerAttachments.ts @@ -0,0 +1,92 @@ +import { + PROVIDER_SEND_TURN_MAX_ATTACHMENTS, + PROVIDER_SEND_TURN_MAX_FILE_BYTES, + PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, +} from "@t3tools/contracts"; + +/** + * Composer intake rules shared by drag, paste, and the file picker. + * + * Kept free of DOM object creation so the accept/reject decisions can be + * tested directly; the caller turns accepted files into draft attachments. + */ + +export function isComposerImageMimeType(mimeType: string): boolean { + return mimeType.trim().toLowerCase().startsWith("image/"); +} + +/** + * Browsers leave `File.type` empty for extensions they don't recognise. The + * contract requires a non-empty mime, and the server derives the stored file + * extension from it, so the generic binary type is the honest fallback. + */ +export function resolveComposerAttachmentMimeType(file: File): string { + const mimeType = file.type.trim(); + return mimeType.length > 0 ? mimeType : "application/octet-stream"; +} + +export function formatComposerAttachmentSize(sizeBytes: number): string { + if (sizeBytes < 1024) return `${sizeBytes} B`; + if (sizeBytes < 1024 * 1024) return `${(sizeBytes / 1024).toFixed(0)} KB`; + return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`; +} + +export interface PlannedComposerAttachment { + file: File; + type: "image" | "file"; + mimeType: string; +} + +export interface ComposerAttachmentIntakePlan { + accepted: PlannedComposerAttachment[]; + /** + * Last rejection reason, surfaced as the thread error the way the + * image-only intake always has. One line is enough: a drop is usually + * rejected for one reason. + */ + error: string | null; +} + +const megabytes = (bytes: number) => `${Math.round(bytes / (1024 * 1024))}MB`; + +/** + * Decides which dropped/pasted/picked files the composer takes. + * + * `allowNonImageFiles` is the Hermes gate: every other provider rejects + * non-images exactly as before, so their intake surface is unchanged. + */ +export function planComposerAttachmentIntake(input: { + files: ReadonlyArray; + existingCount: number; + allowNonImageFiles: boolean; +}): ComposerAttachmentIntakePlan { + const accepted: PlannedComposerAttachment[] = []; + let count = input.existingCount; + let error: string | null = null; + + for (const file of input.files) { + const mimeType = resolveComposerAttachmentMimeType(file); + const isImage = isComposerImageMimeType(mimeType); + if (!isImage && !input.allowNonImageFiles) { + error = `Unsupported file type for '${file.name}'. Please attach image files only.`; + continue; + } + const maxBytes = isImage + ? PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + : PROVIDER_SEND_TURN_MAX_FILE_BYTES; + if (file.size > maxBytes) { + error = `'${file.name}' exceeds the ${megabytes(maxBytes)} attachment limit.`; + continue; + } + if (count >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) { + error = input.allowNonImageFiles + ? `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.` + : `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`; + break; + } + accepted.push({ file, type: isImage ? "image" : "file", mimeType }); + count += 1; + } + + return { accepted, error }; +} diff --git a/apps/web/src/lib/stashImageCompression.ts b/apps/web/src/lib/stashImageCompression.ts index 7f133fb292..7473d296c0 100644 --- a/apps/web/src/lib/stashImageCompression.ts +++ b/apps/web/src/lib/stashImageCompression.ts @@ -173,6 +173,31 @@ async function encodeWithinBudget( * doesn't fit after the fallback passes, returns `null` so the caller can * record it as dropped. */ +/** + * Stash payload for a non-image attachment. There is nothing to re-encode — + * a PDF or archive is not lossy-compressible — so it is stored verbatim when + * it fits the budget and reported as too-large when it does not. + */ +export async function readAttachmentForStash( + file: File, + mimeType: string, + budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS, +): Promise { + let dataUrl: string; + try { + dataUrl = await blobToDataUrl(file, mimeType); + } catch { + return { ok: false, reason: "unreadable" }; + } + if (dataUrl.length > budgetChars) { + return { ok: false, reason: "too-large" }; + } + return { + ok: true, + image: { dataUrl, mimeType, sizeBytes: file.size, recompressed: false }, + }; +} + export async function compressImageForStash( file: File, budgetChars: number = MAX_STASH_IMAGE_DATA_URL_CHARS,