feat(web): accept any file in the composer, render file chips

- drag/drop and paste accept non-image files (staged as name+size
  chips); images keep the existing preview tiles and expand dialog
- timeline renders file attachments as download chips via the signed
  asset URL
- drafts persist an optional attachment type (missing = image, so
  existing persisted drafts decode unchanged; no storage version bump)
- limits and copy: 10 MB per attachment, 8 attachments per message

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Andrei Drăgan RădulețandClaude Fable 5 authored and Julius Marminge committed 2026-07-20 18:08:47 +02:00
1 parent 9b89ef9698
commit 4050afee4d
9 files changed
+150 -53

No files matched your search

+2 -4
View File
@@ -10,7 +10,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";
@@ -193,9 +193,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;
}
+8 -8
View File
@@ -162,7 +162,7 @@ import {
} from "../logicalProject";
import { buildDraftThreadRouteParams } from "../threadRoutes";
import {
type ComposerImageAttachment,
type ComposerAttachment,
type DraftThreadEnvMode,
useComposerDraftStore,
type DraftId,
@@ -261,8 +261,8 @@ import {
} from "../versionSkew";
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 ATTACHMENT_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"] = [];
@@ -1190,7 +1190,7 @@ function ChatViewContent(props: ChatViewProps) {
: null,
);
const promptRef = useRef("");
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
const composerImagesRef = useRef<ComposerAttachment[]>([]);
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
const localComposerRef = useRef<ChatComposerHandle | null>(null);
@@ -4179,11 +4179,11 @@ function ChatViewContent(props: ChatViewProps) {
model: ctxSelectedModel,
models: ctxSelectedProviderModels,
effort: ctxSelectedPromptEffort,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
});
const turnAttachmentsPromise = Promise.all(
composerImagesSnapshot.map(async (image) => ({
type: "image" as const,
type: image.type,
name: image.name,
mimeType: image.mimeType,
sizeBytes: image.sizeBytes,
@@ -4191,7 +4191,7 @@ function ChatViewContent(props: ChatViewProps) {
})),
);
const optimisticAttachments = composerImagesSnapshot.map((image) => ({
type: "image" as const,
type: image.type,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -4253,7 +4253,7 @@ function ChatViewContent(props: ChatViewProps) {
let titleSeed = trimmed;
if (!titleSeed) {
if (firstComposerImageName) {
titleSeed = `Image: ${firstComposerImageName}`;
titleSeed = `${composerImagesSnapshot[0]?.type === "file" ? "File" : "Image"}: ${firstComposerImageName}`;
} else if (composerTerminalContextsSnapshot.length > 0) {
titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);
} else if (composerElementContextsSnapshot.length > 0) {
+42 -22
View File
@@ -49,7 +49,7 @@ import {
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import {
type ComposerImageAttachment,
type ComposerAttachment,
type DraftId,
type PersistedComposerImageAttachment,
useComposerDraftStore,
@@ -101,6 +101,7 @@ import {
BotIcon,
CheckIcon,
CircleAlertIcon,
FileTextIcon,
ListTodoIcon,
PencilRulerIcon,
type LucideIcon,
@@ -130,6 +131,7 @@ import {
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
import { searchProviderSkills } from "../../providerSkillSearch";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { formatAttachmentSizeLabel } from "../../lib/attachmentSize";
import type { ReviewCommentContext } from "../../reviewCommentContext";
const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`;
@@ -425,7 +427,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[];
@@ -516,7 +518,7 @@ export interface ChatComposerProps {
// Refs the parent needs kept in sync
promptRef: React.RefObject<string>;
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
composerImagesRef: React.RefObject<ComposerAttachment[]>;
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
@@ -1175,14 +1177,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],
@@ -1392,6 +1394,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
try {
const dataUrl = await readFileAsDataUrl(image.file);
stagedAttachmentById.set(image.id, {
type: image.type,
id: image.id,
name: image.name,
mimeType: image.mimeType,
@@ -1792,32 +1795,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: "Attach files after answering plan questions.",
});
return;
}
const nextImages: ComposerImageAttachment[] = [];
const nextImages: ComposerAttachment[] = [];
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.`;
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} attachments per message.`;
break;
}
const isImage = file.type.startsWith("image/");
const previewUrl = URL.createObjectURL(file);
nextImages.push({
type: "image",
type: isImage ? "image" : "file",
id: randomUUID(),
name: file.name || "image",
mimeType: file.type,
name: file.name || (isImage ? "image" : "file"),
mimeType: file.type || "application/octet-stream",
sizeBytes: file.size,
previewUrl,
file,
@@ -1842,10 +1842,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => {
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;
event.preventDefault();
addComposerImages(imageFiles);
addComposerImages(files);
};
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
@@ -2352,7 +2350,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId)
}
onExpandImage={(imageId) => {
const preview = buildExpandedImagePreview(composerImages, imageId);
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
imageId,
);
if (preview) onExpandImage(preview);
}}
className="mb-3"
@@ -2403,15 +2404,34 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
.map((image) => (
<div
key={image.id}
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
className={
image.type === "file"
? "relative flex h-16 w-40 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background px-2"
: "relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
}
>
{image.previewUrl ? (
{image.type === "file" ? (
<>
<FileTextIcon className="size-5 shrink-0 text-muted-foreground" />
<div className="min-w-0 pr-5">
<div className="truncate text-xs" title={image.name}>
{image.name}
</div>
<div className="text-[10px] text-muted-foreground/70">
{formatAttachmentSizeLabel(image.sizeBytes)}
</div>
</div>
</>
) : image.previewUrl ? (
<button
type="button"
className="h-full w-full cursor-zoom-in"
aria-label={`Preview ${image.name}`}
onClick={() => {
const preview = buildExpandedImagePreview(composerImages, image.id);
const preview = buildExpandedImagePreview(
composerImages.filter((attachment) => attachment.type === "image"),
image.id,
);
if (!preview) return;
onExpandImage(preview);
}}
@@ -2,13 +2,13 @@ import type { PreviewAnnotationPayload } from "@t3tools/contracts";
import { Frame, MousePointerClick, Paintbrush, PenLine, X } from "lucide-react";
import type { ReactNode } from "react";
import type { ComposerImageAttachment } from "~/composerDraftStore";
import type { ComposerAttachment } from "~/composerDraftStore";
import { formatElementContextLabel, normalizeElementContextSelection } from "~/lib/elementContext";
import { cn } from "~/lib/utils";
interface ComposerPreviewAnnotationCardsProps {
annotations: ReadonlyArray<PreviewAnnotationPayload>;
images: ReadonlyArray<ComposerImageAttachment>;
images: ReadonlyArray<ComposerAttachment>;
onRemove: (annotationId: string) => void;
onExpandImage: (imageId: string) => void;
className?: string;
@@ -49,6 +49,7 @@ import {
CircleAlertIcon,
EyeIcon,
FileDiffIcon,
FileTextIcon,
GlobeIcon,
HammerIcon,
MessageCircleIcon,
@@ -64,6 +65,7 @@ import {
} from "lucide-react";
import { Button } from "../ui/button";
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
import { formatAttachmentSizeLabel } from "~/lib/attachmentSize";
import { ProposedPlanCard } from "./ProposedPlanCard";
import { ChangedFilesTree } from "./ChangedFilesTree";
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
@@ -881,7 +883,10 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
...elementContextState.contexts,
];
const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
const regularImages = userImages.filter(
(image) => image.type === "image" && !image.name.startsWith("preview-annotation-"),
);
const fileAttachments = userImages.filter((attachment) => attachment.type === "file");
const canRevertAgentWork = typeof row.revertTurnCount === "number";
return (
@@ -920,6 +925,38 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
))}
</div>
)}
{fileAttachments.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1.5">
{fileAttachments.map((attachment) => {
const chipContent = (
<>
<FileTextIcon className="size-3.5 shrink-0 text-muted-foreground" />
<span className="max-w-48 truncate">{attachment.name}</span>
<span className="text-muted-foreground/70">
{formatAttachmentSizeLabel(attachment.sizeBytes)}
</span>
</>
);
const chipClassName =
"inline-flex items-center gap-1.5 rounded-md border border-border/80 bg-background/70 px-2 py-1 text-[11px]";
return attachment.previewUrl ? (
<a
key={attachment.id}
href={attachment.previewUrl}
download={attachment.name}
className={`${chipClassName} hover:bg-background`}
aria-label={`Download ${attachment.name}`}
>
{chipContent}
</a>
) : (
<span key={attachment.id} className={chipClassName}>
{chipContent}
</span>
);
})}
</div>
)}
{previewAnnotations.map((annotation, index) => (
<UserMessagePreviewAnnotationCard
key={annotation.id}
+26 -10
View File
@@ -33,7 +33,12 @@ 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 {
type TerminalContextDraft,
ensureInlineTerminalContextPlaceholders,
@@ -79,6 +84,8 @@ if (typeof window !== "undefined" && typeof window.addEventListener === "functio
}
export const PersistedComposerImageAttachment = Schema.Struct({
// Missing on drafts persisted before file attachments existed → "image".
type: Schema.optionalKey(Schema.Literals(["image", "file"])),
id: Schema.String,
name: Schema.String,
mimeType: Schema.String,
@@ -92,6 +99,13 @@ export interface ComposerImageAttachment extends Omit<ChatImageAttachment, "prev
file: File;
}
export interface ComposerFileAttachment extends Omit<ChatFileAttachment, "previewUrl"> {
previewUrl: string;
file: File;
}
export type ComposerAttachment = ComposerImageAttachment | ComposerFileAttachment;
const PersistedTerminalContextDraft = Schema.Struct({
id: Schema.String,
threadId: ThreadId,
@@ -249,7 +263,7 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
*/
export interface ComposerThreadDraftState {
prompt: string;
images: ComposerImageAttachment[];
images: ComposerAttachment[];
nonPersistedImageIds: string[];
persistedAttachments: PersistedComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
@@ -434,8 +448,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,
@@ -551,7 +565,7 @@ const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftSt
stickyActiveProvider: null,
});
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
const EMPTY_IMAGES: ComposerAttachment[] = [];
const EMPTY_IDS: string[] = [];
const EMPTY_PERSISTED_ATTACHMENTS: PersistedComposerImageAttachment[] = [];
const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
@@ -609,7 +623,7 @@ export function createEmptyThreadDraft(): ComposerThreadDraftState {
};
}
function composerImageDedupKey(image: ComposerImageAttachment): string {
function composerImageDedupKey(image: ComposerAttachment): string {
// Keep this independent from File.lastModified so dedupe is stable for hydrated
// images reconstructed from localStorage (which get a fresh lastModified value).
return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`;
@@ -1059,7 +1073,9 @@ function normalizePersistedAttachment(value: unknown): PersistedComposerImageAtt
) {
return null;
}
const type = candidate.type;
return {
...(type === "image" || type === "file" ? { type } : {}),
id,
name,
mimeType,
@@ -2084,21 +2100,21 @@ function hydratePersistedComposerImageAttachment(
function hydrateImagesFromPersisted(
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
): ComposerImageAttachment[] {
): ComposerAttachment[] {
return attachments.flatMap((attachment) => {
const file = hydratePersistedComposerImageAttachment(attachment);
if (!file) return [];
return [
{
type: "image" as const,
type: attachment.type ?? ("image" as const),
id: attachment.id,
name: attachment.name,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
previewUrl: attachment.dataUrl,
file,
} satisfies ComposerImageAttachment,
} satisfies ComposerAttachment,
];
});
}
@@ -2856,7 +2872,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
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)) {
+17 -5
View File
@@ -18,18 +18,30 @@ function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {
return message.role === "assistant" ? "ASSISTANT" : "USER";
}
function attachmentSummary(message: ChatMessage): string | null {
const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");
const count = imageAttachments?.length ?? 0;
function attachmentSummaryOfType(
message: ChatMessage,
type: "image" | "file",
label: string,
): string | null {
const typedAttachments = message.attachments?.filter((attachment) => attachment.type === type);
const count = typedAttachments?.length ?? 0;
if (count === 0) {
return null;
}
const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];
const names = typedAttachments?.slice(0, 3).map((attachment) => attachment.name) ?? [];
const namesSummary = names.join(", ");
const extraCount = count - names.length;
const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";
return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
return `[Attached ${label}${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;
}
function attachmentSummary(message: ChatMessage): string | null {
const summaries = [
attachmentSummaryOfType(message, "image", "image"),
attachmentSummaryOfType(message, "file", "file"),
].filter((summary) => summary !== null);
return summaries.length > 0 ? summaries.join("\n") : null;
}
function buildMessageBlock(message: ChatMessage): string {
+9
View File
@@ -0,0 +1,9 @@
export function formatAttachmentSizeLabel(sizeBytes: number): string {
if (sizeBytes >= 1024 * 1024) {
return `${(sizeBytes / (1024 * 1024)).toFixed(1)} MB`;
}
if (sizeBytes >= 1024) {
return `${(sizeBytes / 1024).toFixed(1)} KB`;
}
return `${sizeBytes} B`;
}
+6 -1
View File
@@ -1,4 +1,5 @@
import type {
ChatFileAttachment as ContractChatFileAttachment,
ChatImageAttachment as ContractChatImageAttachment,
OrchestrationCheckpointFile,
OrchestrationCheckpointSummary,
@@ -35,7 +36,11 @@ export interface ChatImageAttachment extends ContractChatImageAttachment {
readonly previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment;
export interface ChatFileAttachment extends ContractChatFileAttachment {
readonly previewUrl?: string;
}
export type ChatAttachment = ChatImageAttachment | ChatFileAttachment;
export interface ChatMessage extends Omit<OrchestrationMessage, "attachments"> {
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;