feat(web): send any file to Hermes — drag, paste, and a paperclip picker
Intake decisions live in one pure function (planComposerAttachmentIntake) shared by all three entry points, gated on the provider that will actually run the turn: on Hermes threads any file type is accepted (images 10MB, files 10MB, 8 total), everywhere else the image-only behavior — including its exact error strings — is unchanged. The paperclip button and its hidden input only mount on Hermes threads, with a mirrored "Attach files" entry in the compact footer menu since mobile has neither drag nor paste. Non-image files stage as name+size chips in the pending strip and ride the draft store's existing attachment lifecycle (dedupe, persist, hydrate, stash, clear) — the persisted shape carries no variant tag, so the type is re-derived from the mime on hydrate rather than migrating storage. The send path builds type:"file" uploads with the browser mime (empty -> application/octet-stream), and optimistic-message blob previews are now released for every variant, closing a leak where only image blobs were revoked. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
a398258ce6
commit
6998f16f7c
10 files changed
+721
-142
No files matched your search
@@ -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" });
|
||||
});
|
||||
});
|
||||
@@ -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<string>,
|
||||
): 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<string> {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<string>,
|
||||
): 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;
|
||||
}
|
||||
|
||||
@@ -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<ComposerImageAttachment[]>([]);
|
||||
const composerImagesRef = useRef<ComposerAttachment[]>([]);
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
|
||||
const composerElementContextsRef = useRef<ElementContextDraft[]>([]);
|
||||
const localComposerRef = useRef<ChatComposerHandle | null>(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) {
|
||||
|
||||
@@ -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 ? (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onAttachFiles}
|
||||
aria-label="Attach files"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PaperclipIcon className="size-4 shrink-0" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="top">Attach files</TooltipPopup>
|
||||
</Tooltip>
|
||||
</>
|
||||
) : null;
|
||||
|
||||
const agentButton = props.onOpenAgent ? (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
@@ -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<string>;
|
||||
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
|
||||
composerImagesRef: React.RefObject<ComposerAttachment[]>;
|
||||
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
|
||||
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
|
||||
composerRef: React.RefObject<ChatComposerHandle | null>;
|
||||
@@ -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<ComposerPromptEditorHandle>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerFileInputRef = useRef<HTMLInputElement>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement>(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<HTMLInputElement>) => {
|
||||
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<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;
|
||||
// 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<HTMLDivElement>) => {
|
||||
@@ -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 ? (
|
||||
<input
|
||||
ref={composerFileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
className="hidden"
|
||||
aria-hidden="true"
|
||||
tabIndex={-1}
|
||||
onChange={onComposerFileInputChange}
|
||||
/>
|
||||
) : null}
|
||||
<div
|
||||
className={cn(
|
||||
"group rounded-[22px] p-px transition-colors duration-200",
|
||||
@@ -3006,12 +3080,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerPreviewAnnotations.length > 0 && (
|
||||
<ComposerPreviewAnnotationCards
|
||||
annotations={composerPreviewAnnotations}
|
||||
images={composerImages}
|
||||
images={composerPreviewableImages}
|
||||
onRemove={(annotationId) =>
|
||||
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) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
{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);
|
||||
if (!preview) return;
|
||||
onExpandImage(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
.map((image) =>
|
||||
image.type === "file" ? (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative flex h-16 min-w-0 max-w-56 items-center gap-2 overflow-hidden rounded-lg border border-border/80 bg-background pl-2.5 pr-8"
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
<FileIcon
|
||||
className="size-4 shrink-0 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="min-w-0">
|
||||
<span className="block truncate text-xs text-foreground/90">
|
||||
{image.name}
|
||||
</span>
|
||||
<span className="block text-[10px] text-muted-foreground">
|
||||
{formatComposerAttachmentSize(image.sizeBytes)}
|
||||
</span>
|
||||
</span>
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="shrink-0 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
key={image.id}
|
||||
className="relative h-16 w-16 overflow-hidden rounded-lg border border-border/80 bg-background"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(
|
||||
composerPreviewableImages,
|
||||
image.id,
|
||||
);
|
||||
if (!preview) return;
|
||||
onExpandImage(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
{nonPersistedComposerImageIdSet.has(image.id) && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span
|
||||
role="img"
|
||||
aria-label="Draft attachment may not persist"
|
||||
className="absolute left-1 top-1 inline-flex items-center justify-center rounded bg-background/85 p-0.5 text-amber-600"
|
||||
>
|
||||
<CircleAlertIcon className="size-3" />
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-64 whitespace-normal leading-tight"
|
||||
>
|
||||
Draft attachment could not be saved locally and may be lost on
|
||||
navigation.
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="absolute right-1 top-1 bg-background/80 hover:bg-background/90"
|
||||
onClick={() => removeComposerImage(image.id)}
|
||||
aria-label={`Remove ${image.name}`}
|
||||
>
|
||||
<XIcon />
|
||||
</Button>
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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
|
||||
</MenuRadioGroup>
|
||||
</>
|
||||
) : null}
|
||||
{props.onAttachFiles ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuItem onClick={props.onAttachFiles}>
|
||||
<PaperclipIcon className="size-4 shrink-0" />
|
||||
Attach files
|
||||
</MenuItem>
|
||||
</>
|
||||
) : null}
|
||||
{props.onOpenAgent ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
|
||||
@@ -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<typeof vi.fn<(url: string) => 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);
|
||||
|
||||
@@ -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<ChatImageAttachment, "prev
|
||||
file: File;
|
||||
}
|
||||
|
||||
/**
|
||||
* A non-image file staged in the composer. Only Hermes threads can produce
|
||||
* these — every other provider's intake stays image-only — but the draft
|
||||
* state holds them in the same `images` array so attachments share one
|
||||
* lifecycle (dedupe, persist, hydrate, stash, clear) instead of two.
|
||||
*/
|
||||
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 +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<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[] = [];
|
||||
@@ -625,7 +644,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}`;
|
||||
@@ -2100,21 +2119,26 @@ function hydratePersistedComposerImageAttachment(
|
||||
|
||||
export function hydrateImagesFromPersisted(
|
||||
attachments: ReadonlyArray<PersistedComposerImageAttachment>,
|
||||
): 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<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)) {
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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<File>;
|
||||
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 };
|
||||
}
|
||||
@@ -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<CompressStashImageResult> {
|
||||
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,
|
||||
|
||||
Reference in new issue
Block a user