Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(chat): upload arbitrary original attachments

Steven Enamakelfb71a55cf077
diff --git a/app/src/components/assistant-ui/__tests__/UserActionBar.test.tsx b/app/src/components/assistant-ui/__tests__/UserActionBar.test.tsx
index d9e4e83694..816e514122 100644
--- a/app/src/components/assistant-ui/__tests__/UserActionBar.test.tsx
+++ b/app/src/components/assistant-ui/__tests__/UserActionBar.test.tsx
@@ -77,6 +77,16 @@ describe('User-message action bar — capability-gated Edit (#5897)', () => {
).toEqual([file]);
});
+ it('extracts arbitrary clipboard files with empty item MIME', () => {
+ const file = new File(['original'], 'archive.zip');
+ expect(
+ extractComposerPasteFiles({
+ items: [{ kind: 'file', type: '', getAsFile: () => file }],
+ files: [],
+ } as unknown as DataTransfer)
+ ).toEqual([file]);
+ });
+
it('renders the user message and its action bar', async () => {
const { container } = renderThreadWithOneUserMessage();
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index 80d3e091d4..9559e695ff 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -922,7 +922,7 @@ export function extractComposerPasteFiles(
clipboardData: DataTransfer | null | undefined
): globalThis.File[] {
const itemFiles = Array.from(clipboardData?.items ?? [])
- .filter(item => item.kind === 'file' && /^(image|video)\//.test(item.type))
+ .filter(item => item.kind === 'file')
.map(item => item.getAsFile())
.filter((file): file is globalThis.File => file !== null);
return itemFiles.length > 0 ? itemFiles : Array.from(clipboardData?.files ?? []);
diff --git a/app/src/components/chat/AttachmentPreview.tsx b/app/src/components/chat/AttachmentPreview.tsx
index 3076e3d7c6..e9a9e126ad 100644
--- a/app/src/components/chat/AttachmentPreview.tsx
+++ b/app/src/components/chat/AttachmentPreview.tsx
@@ -31,11 +31,13 @@ export default function AttachmentPreview({
/>
) : attachment.kind === 'video' ? (
<div className="relative w-8 h-8 shrink-0">
- <img
- src={attachment.previewUri ?? attachment.dataUri}
- alt={attachment.file.name}
- className="w-8 h-8 rounded object-cover"
- />
+ {attachment.previewUri && (
+ <img
+ src={attachment.previewUri}
+ alt={attachment.file.name}
+ className="w-8 h-8 rounded object-cover"
+ />
+ )}
<span className="absolute inset-0 flex items-center justify-center">
<svg
className="w-3.5 h-3.5 text-content-inverted drop-shadow-sm"
diff --git a/app/src/components/chat/ChatComposer.tsx b/app/src/components/chat/ChatComposer.tsx
index c0e6bbb2c3..0e9199a1ce 100644
--- a/app/src/components/chat/ChatComposer.tsx
+++ b/app/src/components/chat/ChatComposer.tsx
@@ -200,7 +200,6 @@ function ChatComposerBody({
inlineCompletionSuffix,
isComposingTextRef,
maxAttachments,
- allowedMimeTypes,
attachmentsEnabled,
micEnabled = true,
placeholder,
@@ -295,7 +294,7 @@ function ChatComposerBody({
void onAttachFiles(files);
};
- // Clipboard paste: pull image/video files out of the paste payload (e.g. a
+ // Clipboard paste: pull files out of the paste payload (e.g. a
// screenshot copied to the clipboard) and attach them; leave plain-text paste
// untouched so normal typing still works. `addAttachmentOnPaste={false}` on
// the primitive keeps assistant-ui's own paste-to-attach path out of the way —
@@ -305,17 +304,16 @@ function ChatComposerBody({
// Prefer FileList: a webview can expose a clipboard image there without
// a usable DataTransferItem. Use items only as a fallback, so the same
// screenshot represented in both lists is attached once.
- const isMedia = (file: File) => /^(image|video)\//.test(file.type);
- let files = Array.from(e.clipboardData?.files ?? []).filter(isMedia);
+ let files = Array.from(e.clipboardData?.files ?? []);
if (files.length === 0) {
files = Array.from(e.clipboardData?.items ?? [])
.filter(item => item.kind === 'file')
.map(item => item.getAsFile())
- .filter((file): file is File => file !== null && isMedia(file));
+ .filter((file): file is File => file !== null);
}
if (files.length === 0) return;
e.preventDefault();
- debug('[chat-composer] paste: ingesting %d media file(s)', files.length);
+ debug('[chat-composer] paste: ingesting %d file(s)', files.length);
void onAttachFiles(files);
};
@@ -362,12 +360,7 @@ function ChatComposerBody({
<input
ref={fileInputRef}
type="file"
- // No `accept` filter: Chromium 146 / CEF on macOS greys out valid files
- // at the native open panel regardless of the filter shape (MIME, mixed,
- // or extension-only). Selection is gated in `onAttachFiles` →
- // `validateAndReadFile` instead (rejects unsupported types + images on
- // non-vision models). `allowedMimeTypes` is kept for that JS validation.
- accept={allowedMimeTypes.length ? allowedMimeTypes.join(',') : undefined}
+ // Accept originals of any type; the core chooses native or tool handling.
multiple
className="hidden"
onChange={e => {
diff --git a/app/src/components/chat/__tests__/AttachmentPreview.test.tsx b/app/src/components/chat/__tests__/AttachmentPreview.test.tsx
index 6d2bffe408..8102478333 100644
--- a/app/src/components/chat/__tests__/AttachmentPreview.test.tsx
+++ b/app/src/components/chat/__tests__/AttachmentPreview.test.tsx
@@ -54,6 +54,29 @@ describe('AttachmentPreview', () => {
expect(screen.queryByAltText('doc.pdf')).not.toBeInTheDocument();
});
+ it('renders a video chip without using original video bytes as an image', () => {
+ const file = new File(['original'], 'clip.mp4', { type: 'video/mp4' });
+ render(
+ <AttachmentPreview
+ attachments={[
+ {
+ id: 'video-no-preview',
+ kind: 'video',
+ file,
+ dataUri: 'data:video/mp4;base64,original',
+ mimeType: 'video/mp4',
+ originalSizeBytes: 8,
+ payloadSizeBytes: 8,
+ compressed: false,
+ },
+ ]}
+ onRemove={vi.fn()}
+ />
+ );
+ expect(screen.getByText('clip.mp4')).toBeInTheDocument();
+ expect(screen.queryByRole('img')).not.toBeInTheDocument();
+ });
+
it('renders a video poster thumbnail with a play overlay', () => {
const file = new File([new Uint8Array(64)], 'clip.mp4', { type: 'video/mp4' });
const att = makeAttachment({
diff --git a/app/src/components/chat/__tests__/ChatComposer.test.tsx b/app/src/components/chat/__tests__/ChatComposer.test.tsx
index 566163c7be..6e43420240 100644
--- a/app/src/components/chat/__tests__/ChatComposer.test.tsx
+++ b/app/src/components/chat/__tests__/ChatComposer.test.tsx
@@ -463,7 +463,7 @@ describe('ChatComposer', () => {
expect(onAttachFiles).not.toHaveBeenCalled();
});
- it('ignores unreadable clipboard items and non-media files', () => {
+ it('ignores unreadable clipboard items while accepting arbitrary files', () => {
const onAttachFiles = vi.fn().mockResolvedValue(undefined);
renderComposer({ onAttachFiles });
const file = new File(['text'], 'note.txt', { type: 'text/plain' });
@@ -476,8 +476,8 @@ describe('ChatComposer', () => {
],
},
});
- expect(onAttachFiles).not.toHaveBeenCalled();
- expect(notPrevented).toBe(true);
+ expect(onAttachFiles).toHaveBeenCalledWith([file]);
+ expect(notPrevented).toBe(false);
});
it('ignores plain-text paste (no media items)', () => {
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsx
index f2af22488d..94367f5b58 100644
--- a/app/src/features/conversations/Conversations.tsx
+++ b/app/src/features/conversations/Conversations.tsx
@@ -505,48 +505,21 @@ const Conversations = ({
});
}, []);
- // Whether the resolved model accepts image input.
- // Managed tiers do; custom/BYOK models only when the user flagged them. Gates
- // the composer's image-attachment affordance (docs flow regardless). Resolved
- // against the non-attachment hint so the affordance is stable as you attach.
- const [modelSupportsVision, setModelSupportsVision] = useState(false);
- // Whether a vision-capable delegate (the `vision` sub-agent) is reachable.
- // When it is, an image may be attached and routed to that sub-agent even if
- // the active orchestrator model is non-vision — the orchestrator sees a text
- // placeholder and delegates the image to the vision sub-agent. Resolved from
- // the `vision` workload route (the managed default on the managed backend, or the BYOK
- // model routed to the Vision workload).
- const [visionDelegateAvailable, setVisionDelegateAvailable] = useState(false);
-
useEffect(() => {
let cancelled = false;
(async () => {
try {
- // Resolve the standard chat model so `modelSupportsVision` reflects the
- // normal agent path, AND the vision workload so we know whether a
- // vision sub-agent can take the image. Documents are text-extracted so
- // any model handles them.
const hint = composerModelOverride ?? CHAT_MODEL_HINT;
- const [res, visionRes] = await Promise.all([
- callCoreRpc<{ model: string; vision?: boolean }>({
- method: 'openhuman.inference_resolve_model',
- params: { hint },
- }),
- callCoreRpc<{ model: string; vision?: boolean }>({
- method: 'openhuman.inference_resolve_model',
- params: { hint: 'hint:vision' },
- }).catch(() => ({ model: '', vision: false })),
- ]);
+ const res = await callCoreRpc<{ model: string }>({
+ method: 'openhuman.inference_resolve_model',
+ params: { hint },
+ });
if (!cancelled) {
setResolvedModel(res.model);
- setModelSupportsVision(res.vision === true);
- setVisionDelegateAvailable(visionRes.vision === true);
}
} catch {
if (!cancelled) {
setResolvedModel(null);
- setModelSupportsVision(false);
- setVisionDelegateAvailable(false);
}
}
})();
@@ -1061,35 +1034,17 @@ const Conversations = ({
// can fire before React re-renders. Both would then seed their budget from
// the same snapshot and each admit a full quota.
const admitted = attachmentsRef.current;
- let acceptedFileCount = admitted.filter(attachment => attachment.kind === 'file').length;
- // Images and videos share one image-marker budget (video = its frames), so
- // track consumed markers rather than per-kind counts.
+ let acceptedFileCount = admitted.filter(attachment => attachment.kind !== 'image').length;
+ // Only original images consume image markers; videos consume file slots.
let acceptedImageMarkers = admitted.reduce(
(sum, attachment) => sum + imageMarkerCost(attachment.kind),
0
);
for (const file of Array.from(files)) {
- const result = await validateAndReadFile(
- file,
- acceptedImageMarkers,
- acceptedFileCount,
- // Allow images AND video when the active model is vision-capable OR a
- // vision sub-agent can take it (orchestrator delegates the image/frames
- // onward). Video is sampled into still frames that ride the same path.
- modelSupportsVision || visionDelegateAvailable
- );
+ const result = await validateAndReadFile(file, acceptedImageMarkers, acceptedFileCount);
if ('error' in result) {
const { error } = result;
- if (error.code === 'image_not_supported') {
- setAttachError(
- chatSendError('attachment_invalid', t('chat.attachment.imageNotSupported'))
- );
- } else if (error.code === 'video_not_supported') {
- setAttachError(
- chatSendError('attachment_invalid', t('chat.attachment.videoNotSupported'))
- );
- } else if (error.code === 'too_many') {
- // image/video share the image-marker budget → tooMany; files separate.
+ if (error.code === 'too_many') {
const key =
error.kind === 'file' ? 'chat.attachment.tooManyFiles' : 'chat.attachment.tooMany';
setAttachError(
@@ -1103,14 +1058,12 @@ const Conversations = ({
t('chat.attachment.tooLarge').replace('{max}', `${maxMb} MB`)
)
);
- } else if (error.code === 'unsupported_type') {
- setAttachError(chatSendError('attachment_invalid', t('chat.attachment.unsupportedType')));
} else {
setAttachError(chatSendError('attachment_invalid', t('chat.attachment.readFailed')));
}
return;
}
- if (result.attachment.kind === 'file') {
+ if (result.attachment.kind !== 'image') {
acceptedFileCount++;
} else {
acceptedImageMarkers += imageMarkerCost(result.attachment.kind);
@@ -1216,7 +1169,7 @@ const Conversations = ({
// Poster (first frame) per attachment, index-aligned with
// attachmentKinds — only video entries carry one; others null.
attachmentPosters: pendingAttachments.map(a =>
- a.kind === 'video' ? (a.previewUri ?? a.dataUri) : null
+ a.kind === 'video' ? (a.previewUri ?? null) : null
),
attachmentCompressed: pendingAttachments.map(a => a.compressed),
}
@@ -1355,7 +1308,7 @@ const Conversations = ({
// Poster (first frame) per attachment, index-aligned with
// attachmentKinds — only video entries carry one; others null.
attachmentPosters: pendingAttachments.map(a =>
- a.kind === 'video' ? (a.previewUri ?? a.dataUri) : null
+ a.kind === 'video' ? (a.previewUri ?? null) : null
),
attachmentCompressed: pendingAttachments.map(a => a.compressed),
}
diff --git a/app/src/lib/attachments.test.ts b/app/src/lib/attachments.test.ts
index e9c48f44b5..0a99123660 100644
--- a/app/src/lib/attachments.test.ts
+++ b/app/src/lib/attachments.test.ts
@@ -17,7 +17,6 @@ import {
isVideoMimeType,
parseMessageImages,
validateAndReadFile,
- VIDEO_FRAME_COUNT,
videoFrameExtractor,
} from './attachments';
@@ -74,6 +73,62 @@ describe('fileToDataUri', () => {
});
describe('validateAndReadFile', () => {
+ it('preserves unknown MIME, filename and original bytes in the upload marker', async () => {
+ const file = new File([Uint8Array.of(0, 255, 128)], 'archive ] résumé.bin');
+ const result = await validateAndReadFile(file, 0);
+ expect('attachment' in result).toBe(true);
+ if ('attachment' in result) {
+ expect(result.attachment.mimeType).toBe('application/octet-stream');
+ expect(result.attachment.dataUri).toBe(
+ 'data:application/octet-stream;name=archive%20%5D%20r%C3%A9sum%C3%A9.bin;base64,AP+A'
+ );
+ }
+ });
+
+ it('uses reversible gzip transport while preserving original filename and MIME', async () => {
+ const original = new TextEncoder().encode('a'.repeat(4096));
+ const file = new File([original], 'Report.TXT', { type: 'text/plain' });
+ Object.defineProperty(file, 'stream', {
+ value: () =>
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(original);
+ controller.close();
+ },
+ }),
+ });
+ try {
+ const result = await validateAndReadFile(file, 0);
+ expect('attachment' in result).toBe(true);
+ if ('attachment' in result) {
+ expect(result.attachment.compressed).toBe(true);
+ expect(result.attachment.dataUri).toMatch(
+ /^data:application\/gzip;original_mime=text%2Fplain;name=Report.TXT;base64,/
+ );
+ const encoded = result.attachment.dataUri.split(',')[1];
+ const bytes = Uint8Array.from(atob(encoded), char => char.charCodeAt(0));
+ const stream = new ReadableStream({
+ start(controller) {
+ controller.enqueue(bytes);
+ controller.close();
+ },
+ });
+ const recovered = await new Response(
+ stream.pipeThrough(new DecompressionStream('gzip'))
+ ).arrayBuffer();
+ expect(Array.from(new Uint8Array(recovered))).toEqual(Array.from(original));
+ expect(result.attachment.originalSizeBytes).toBe(original.length);
+ }
+ } finally {
+ vi.unstubAllGlobals();
+ }
+ });
+
+ it('accepts audio originals without transcribing them', async () => {
+ const result = await validateAndReadFile(makeFile('voice.mp3', 'audio/mpeg', 3), 0);
+ expect('attachment' in result && result.attachment.kind).toBe('file');
+ });
+
it('rejects when at max image count', async () => {
const file = makeFile('x.png', 'image/png');
const result = await validateAndReadFile(file, ATTACHMENT_MAX_IMAGES);
@@ -83,16 +138,13 @@ describe('validateAndReadFile', () => {
}
});
- it('rejects unsupported MIME types', async () => {
+ it('accepts arbitrary MIME types', async () => {
const file = makeFile('vector.svg', 'image/svg+xml');
const result = await validateAndReadFile(file, 0);
- expect('error' in result).toBe(true);
- if ('error' in result) {
- expect(result.error.code).toBe('unsupported_type');
- }
+ expect('attachment' in result && result.attachment.kind).toBe('file');
});
- it('rejects non-extractable documents (docx/pptx/xlsx) the agent cannot read', async () => {
+ it('accepts Office documents and archives as original files', async () => {
for (const mime of [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
@@ -100,7 +152,7 @@ describe('validateAndReadFile', () => {
'application/zip',
]) {
const result = await validateAndReadFile(makeFile('f', mime, 8), 0);
- expect('error' in result && result.error.code).toBe('unsupported_type');
+ expect('attachment' in result && result.attachment.kind).toBe('file');
}
});
@@ -111,9 +163,9 @@ describe('validateAndReadFile', () => {
}
});
- it('rejects an image when allowImages is false (non-vision model)', async () => {
+ it('accepts an image even for a non-vision model', async () => {
const result = await validateAndReadFile(makeFile('p.png', 'image/png', 8), 0, 0, false);
- expect('error' in result && result.error.code).toBe('image_not_supported');
+ expect('attachment' in result && result.attachment.kind).toBe('image');
});
it('still accepts a document when allowImages is false', async () => {
@@ -155,7 +207,7 @@ describe('validateAndReadFile', () => {
if ('attachment' in result) {
expect(result.attachment.mimeType).toBe('image/png');
expect(result.attachment.kind).toBe('image');
- expect(result.attachment.dataUri).toMatch(/^data:image\/png;base64,/);
+ expect(result.attachment.dataUri).toMatch(/^data:image\/png;name=ok.png;base64,/);
expect(result.attachment.file).toBe(file);
expect(result.attachment.compressed).toBe(false);
}
@@ -168,7 +220,7 @@ describe('validateAndReadFile', () => {
if ('attachment' in result) {
expect(result.attachment.mimeType).toBe('application/pdf');
expect(result.attachment.kind).toBe('file');
- expect(result.attachment.dataUri).toMatch(/^data:application\/pdf;base64,/);
+ expect(result.attachment.dataUri).toMatch(/^data:application\/pdf;name=doc.pdf;base64,/);
}
});
@@ -208,64 +260,47 @@ describe('video attachments', () => {
expect(attachmentKindForMime('video/mp4')).toBe('video');
});
- it('costs 1 image marker per image and VIDEO_FRAME_COUNT per video', () => {
+ it('budgets originals rather than video preview frames', async () => {
expect(imageMarkerCost('image')).toBe(1);
- expect(imageMarkerCost('video')).toBe(VIDEO_FRAME_COUNT);
+ expect(imageMarkerCost('video')).toBe(0);
expect(imageMarkerCost('file')).toBe(0);
- });
-
- it('rejects video when allowImages is false (non-vision model)', async () => {
- const result = await validateAndReadFile(makeFile('clip.mp4', 'video/mp4', 8), 0, 0, false);
- expect('error' in result && result.error.code).toBe('video_not_supported');
- });
-
- it('rejects video over the video size limit', async () => {
- const big = makeFile('big.mp4', 'video/mp4', ATTACHMENT_MAX_VIDEO_SIZE_BYTES + 1);
- const result = await validateAndReadFile(big, 0, 0, true);
- expect('error' in result && result.error.code).toBe('too_large');
- });
-
- it('rejects video when its frames would exceed the shared image-marker budget', async () => {
- // Budget full of images already → no room for a video's frames.
const result = await validateAndReadFile(
makeFile('clip.mp4', 'video/mp4', 8),
ATTACHMENT_MAX_IMAGES,
0,
- true
+ false
);
- expect('error' in result && result.error.code).toBe('too_many');
- // Reported as the image budget (frames are images to the model).
- expect('error' in result && result.error.code === 'too_many' && result.error.kind).toBe(
- 'image'
+ expect('attachment' in result && result.attachment.kind).toBe('video');
+ });
+
+ it('rejects video over the original file size limit', async () => {
+ const result = await validateAndReadFile(
+ makeFile('big.mp4', 'video/mp4', ATTACHMENT_MAX_VIDEO_SIZE_BYTES + 1),
+ 0
);
+ expect('error' in result && result.error.code).toBe('too_large');
+ expect(ATTACHMENT_MAX_VIDEO_SIZE_BYTES).toBe(ATTACHMENT_MAX_FILE_SIZE_BYTES);
});
- it('rejects a video that partially overflows the budget (images + frames)', async () => {
- // One image used (1 marker); a video costs VIDEO_FRAME_COUNT more. With the
- // default budget of 4, 1 + 2 = 3 fits, but seed close to the cap to overflow.
- const used = ATTACHMENT_MAX_IMAGES - (VIDEO_FRAME_COUNT - 1); // leaves < cost
- const result = await validateAndReadFile(makeFile('c.mp4', 'video/mp4', 8), used, 0, true);
+ it('rejects video when the file count is full', async () => {
+ const result = await validateAndReadFile(makeFile('clip.mp4', 'video/mp4', 8), 0, 4);
expect('error' in result && result.error.code).toBe('too_many');
});
- it('samples frames and returns a video attachment within budget', async () => {
- const frames = ['data:image/jpeg;base64,f1', 'data:image/jpeg;base64,f2'];
- vi.spyOn(videoFrameExtractor, 'extract').mockResolvedValue(frames);
- const file = makeFile('clip.mp4', 'video/mp4', 4096);
- const result = await validateAndReadFile(file, 0, 0, true);
+ it('retains the exact video bytes without requiring a browser decoder', async () => {
+ const decode = vi
+ .spyOn(videoFrameExtractor, 'extract')
+ .mockRejectedValue(new Error('codec unavailable'));
+ const file = new File([Uint8Array.of(1, 2, 3, 4)], 'clip.mp4', { type: 'video/mp4' });
+ const result = await validateAndReadFile(file, 0);
expect('attachment' in result).toBe(true);
if ('attachment' in result) {
- expect(result.attachment.kind).toBe('video');
- expect(result.attachment.frames).toEqual(frames);
- expect(result.attachment.previewUri).toBe(frames[0]);
- expect(result.attachment.file).toBe(file);
+ expect(result.attachment.dataUri).toBe('data:video/mp4;name=clip.mp4;base64,AQIDBA==');
+ expect(buildMessageWithAttachments('', [result.attachment])).toBe(
+ '[FILE:data:video/mp4;name=clip.mp4;base64,AQIDBA==]'
+ );
}
- });
-
- it('fails when no frames could be extracted', async () => {
- vi.spyOn(videoFrameExtractor, 'extract').mockResolvedValue([]);
- const result = await validateAndReadFile(makeFile('clip.mp4', 'video/mp4', 8), 0, 0, true);
- expect('error' in result && result.error.code).toBe('read_failed');
+ expect(decode).not.toHaveBeenCalled();
});
});
@@ -355,7 +390,7 @@ describe('extractVideoFrames (DOM-mocked)', () => {
expect(frames.length).toBe(2);
});
- it('propagates a read_failed error when the video fails to decode', async () => {
+ it('the explicit preview helper rejects a video that fails to decode', async () => {
const realCreate = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation((tag: string) => {
if (tag === 'video') {
@@ -375,8 +410,7 @@ describe('extractVideoFrames (DOM-mocked)', () => {
if (tag === 'canvas') return makeFakeCanvas() as unknown as HTMLElement;
return realCreate(tag as keyof HTMLElementTagNameMap);
});
- const result = await validateAndReadFile(makeFile('bad.mp4', 'video/mp4', 8), 0, 0, true);
- expect('error' in result && result.error.code).toBe('read_failed');
+ await expect(extractVideoFrames(makeFile('bad.mp4', 'video/mp4', 8))).rejects.toThrow();
});
});
@@ -385,19 +419,17 @@ describe('buildMessageWithAttachments', () => {
expect(buildMessageWithAttachments('hello', [])).toBe('hello');
});
- it('expands a video into one IMAGE marker per sampled frame', () => {
+ it('sends the original video even when optional preview frames exist', () => {
const video = makeAttachment({
kind: 'video',
file: makeFile('clip.mp4', 'video/mp4'),
mimeType: 'video/mp4',
- dataUri: 'data:image/jpeg;base64,f1',
+ dataUri: 'data:video/mp4;base64,original',
previewUri: 'data:image/jpeg;base64,f1',
frames: ['data:image/jpeg;base64,f1', 'data:image/jpeg;base64,f2'],
});
const result = buildMessageWithAttachments('watch', [video]);
- expect(result).toBe(
- 'watch [IMAGE:data:image/jpeg;base64,f1] [IMAGE:data:image/jpeg;base64,f2]'
- );
+ expect(result).toBe('watch [FILE:data:video/mp4;base64,original]');
});
it('appends IMAGE markers after the text', () => {
diff --git a/app/src/lib/attachments.ts b/app/src/lib/attachments.ts
index 00a6ec1809..a324f1fcb5 100644
--- a/app/src/lib/attachments.ts
+++ b/app/src/lib/attachments.ts
@@ -1,7 +1,7 @@
/**
* Utilities for multimodal chat attachments.
*
- * Images are embedded as `[IMAGE:<data-uri>]` markers. Other supported files
+ * Images are embedded as `[IMAGE:<data-uri>]` markers. Other files
* are embedded as `[FILE:<data-uri>]` markers. The Rust agent harness
* (`agent/multimodal.rs`) parses, validates, and expands both shapes before
* the provider call.
@@ -34,50 +34,25 @@ const ALLOWED_FILE_MIME_TYPES = [
export type AllowedFileMimeType = (typeof ALLOWED_FILE_MIME_TYPES)[number];
-// Video formats accepted by the composer. The original video is never sent to
-// the provider — instead we sample a few still frames client-side and forward
-// them through the existing `[IMAGE:]` vision path (see `extractVideoFrames` +
-// `buildMessageWithAttachments`). So a vision-capable tier is required, the same
-// gate as images; audio and motion between frames are not conveyed.
+// Known video types select a video chip; every other MIME is still accepted
+// as an original file. Capability routing and extraction belong to the core.
const ALLOWED_VIDEO_MIME_TYPES = ['video/mp4', 'video/quicktime', 'video/webm'] as const;
-
export type AllowedVideoMimeType = (typeof ALLOWED_VIDEO_MIME_TYPES)[number];
-export type AllowedAttachmentMimeType =
- | AllowedImageMimeType
- | AllowedFileMimeType
- | AllowedVideoMimeType;
+export type AllowedAttachmentMimeType = string;
export type AttachmentKind = 'image' | 'file' | 'video';
-
export const ALLOWED_ATTACHMENT_MIME_TYPES = [
...ALLOWED_IMAGE_MIME_TYPES,
...ALLOWED_FILE_MIME_TYPES,
...ALLOWED_VIDEO_MIME_TYPES,
] as const;
-// Document formats the backend actually text-extracts (PDF via pdf_extract;
-// TXT/Markdown via UTF-8). DOCX/PPTX/XLSX/ZIP are intentionally excluded — the
-// agent would only see a reference stub, not their content. `text/csv` is also
-// deliberately left out: the backend *can* extract it, but the chat composer is
-// scoped to PDF/TXT/Markdown by product decision (revisit here if CSV is wanted).
-// Used by the ingest validator below, not by a native `accept` filter:
-// Chromium/CEF on macOS greys valid files at the open panel regardless of the
-// filter shape, so selection is gated in `validateAndReadFile` after the user
-// picks, not at the dialog.
-const EXTRACTABLE_FILE_MIME_TYPES = ['application/pdf', 'text/plain', 'text/markdown'] as const;
-
-// Shared image-marker budget per message. Images cost 1 marker each; a video
-// costs VIDEO_FRAME_COUNT markers (its sampled frames). Mirrors the core default
-// `multimodal.max_images` (crates/openhuman-core/src/config/schema/tools/multimodal.rs) — the
-// core counts every `[IMAGE:]` marker (frames included) and errors on overflow,
-// so the composer must budget images + video frames against this single cap.
+// Original image uploads and all other original files have separate budgets.
export const ATTACHMENT_MAX_IMAGES = 4;
export const ATTACHMENT_MAX_FILES = 4;
export const ATTACHMENT_MAX_IMAGE_SIZE_BYTES = 8 * 1024 * 1024; // 8 MB
export const ATTACHMENT_MAX_FILE_SIZE_BYTES = 16 * 1024 * 1024; // 16 MB
-export const ATTACHMENT_MAX_VIDEO_SIZE_BYTES = 50 * 1024 * 1024; // 50 MB
-// Still frames sampled from a video and forwarded as `[IMAGE:]` markers. 2 keeps
-// a clip within the 4-marker budget alongside other attachments (e.g. 1 video +
-// 2 images, or 2 videos).
+export const ATTACHMENT_MAX_VIDEO_SIZE_BYTES = ATTACHMENT_MAX_FILE_SIZE_BYTES;
+// Default number of stills for callers explicitly requesting a video preview.
export const VIDEO_FRAME_COUNT = 2;
export interface Attachment {
@@ -90,18 +65,13 @@ export interface Attachment {
originalSizeBytes: number;
payloadSizeBytes: number;
compressed: boolean;
- // Only set for `kind: 'video'`: the still frames sampled from the clip,
- // expanded into `[IMAGE:]` markers at send time. The chip itself shows a
- // single poster (the first frame) via `previewUri`.
+ // Optional preview frames only; originals are always sent as FILE markers.
frames?: string[];
}
type AttachmentError =
- | { code: 'unsupported_type'; mimeType: string }
| { code: 'too_large'; sizeBytes: number; maxBytes: number }
| { code: 'too_many'; kind: AttachmentKind; max: number }
- | { code: 'image_not_supported' }
- | { code: 'video_not_supported' }
| { code: 'read_failed'; reason: string };
export function isAllowedMimeType(mime: string): mime is AllowedImageMimeType {
@@ -112,31 +82,6 @@ export function isVideoMimeType(mime: string): mime is AllowedVideoMimeType {
return (ALLOWED_VIDEO_MIME_TYPES as readonly string[]).includes(mime);
}
-/**
- * The exact MIME set the ingest validator accepts — images plus the
- * text-extractable documents. A strict subset of {@link AllowedAttachmentMimeType}
- * (which also lists reference-only types like CSV/DOCX/ZIP that we reject).
- */
-type SupportedAttachmentMimeType =
- | AllowedImageMimeType
- | AllowedVideoMimeType
- | (typeof EXTRACTABLE_FILE_MIME_TYPES)[number];
-
-/**
- * Only accepts formats the backend actually reads — images, plus the
- * text-extractable documents (PDF via
- * pdf_extract; TXT/Markdown via UTF-8). DOCX/PPTX/XLSX/ZIP are excluded so they
- * can't be attached as content-less reference stubs. Applied on every ingest
- * path (picker, drag-drop, paste).
- */
-function isSupportedAttachmentMimeType(mime: string): mime is SupportedAttachmentMimeType {
- return (
- (ALLOWED_IMAGE_MIME_TYPES as readonly string[]).includes(mime) ||
- (ALLOWED_VIDEO_MIME_TYPES as readonly string[]).includes(mime) ||
- (EXTRACTABLE_FILE_MIME_TYPES as readonly string[]).includes(mime)
- );
-}
-
export function attachmentKindForMime(mime: AllowedAttachmentMimeType): AttachmentKind {
if (isAllowedMimeType(mime)) return 'image';
if (isVideoMimeType(mime)) return 'video';
@@ -154,8 +99,11 @@ export function fileToDataUri(file: Blob): Promise<string> {
}
async function blobToDataUri(blob: Blob, mimeType: string): Promise<string> {
- const namedBlob = new Blob([blob], { type: mimeType });
- return fileToDataUri(namedBlob);
+ // Blob normalizes MIME text to lowercase, including arbitrary parameters.
+ // Insert the encoded filename after reading so its case stays intact.
+ const typedBlob = new Blob([blob], { type: mimeType.split(';')[0] });
+ const uri = await fileToDataUri(typedBlob);
+ return `data:${mimeType};base64,${uri.slice(uri.indexOf(',') + 1)}`;
}
async function gzipBlob(file: File): Promise<Blob | null> {
@@ -201,7 +149,7 @@ async function buildAttachmentDataUri(
return { dataUri, payloadSizeBytes: compressed.size, compressed: true };
}
- const dataUri = await fileToDataUri(file);
+ const dataUri = await blobToDataUri(file, `${mimeType};name=${encodeDataUriParam(file.name)}`);
debug(
'[chat:attachments] compression:skipped name=%s original=%d compressed=%s',
file.name,
@@ -302,47 +250,27 @@ export function extractVideoFrames(file: File, count?: number): Promise<string[]
return videoFrameExtractor.extract(file, count);
}
-/** Image-marker cost of an attachment kind (video = its sampled frames). */
+/** Number of image markers sent for an original attachment. */
export function imageMarkerCost(kind: AttachmentKind): number {
- if (kind === 'image') return 1;
- if (kind === 'video') return VIDEO_FRAME_COUNT;
- return 0;
+ return kind === 'image' ? 1 : 0;
}
export async function validateAndReadFile(
file: File,
- // Image-marker slots already consumed this message: 1 per image + VIDEO_FRAME_COUNT
- // per video. Images and videos share one budget (ATTACHMENT_MAX_IMAGES) because
- // the core counts every `[IMAGE:]` marker — frames included — and rejects overflow.
existingImageMarkers: number,
existingFileCount = 0,
- // When `false` (the active chat model isn't vision-capable), image AND video
- // files are rejected (video is conveyed as sampled frames through the vision
- // path); documents (PDF/Word/etc.) still flow. Defaults `true` so non-chat
- // callers are unaffected.
- allowImages = true
+ // Kept for compatibility with callers: capabilities affect core routing,
+ // never whether an original may be uploaded.
+ _allowImages = true
): Promise<{ attachment: Attachment } | { error: AttachmentError }> {
- if (!isSupportedAttachmentMimeType(file.type)) {
- return { error: { code: 'unsupported_type', mimeType: file.type || 'unknown' } };
- }
-
- const kind = attachmentKindForMime(file.type);
- if (!allowImages && kind === 'image') {
- return { error: { code: 'image_not_supported' } };
- }
- if (!allowImages && kind === 'video') {
- return { error: { code: 'video_not_supported' } };
- }
-
- if (kind === 'file') {
+ const mimeType = file.type || 'application/octet-stream';
+ const kind = attachmentKindForMime(mimeType);
+ if (kind !== 'image') {
if (existingFileCount >= ATTACHMENT_MAX_FILES) {
return { error: { code: 'too_many', kind: 'file', max: ATTACHMENT_MAX_FILES } };
}
- } else {
- // image or video: budget against the shared image-marker cap.
- if (existingImageMarkers + imageMarkerCost(kind) > ATTACHMENT_MAX_IMAGES) {
- return { error: { code: 'too_many', kind: 'image', max: ATTACHMENT_MAX_IMAGES } };
- }
+ } else if (existingImageMarkers >= ATTACHMENT_MAX_IMAGES) {
+ return { error: { code: 'too_many', kind: 'image', max: ATTACHMENT_MAX_IMAGES } };
}
const maxBytes =
@@ -356,30 +284,7 @@ export async function validateAndReadFile(
}
try {
- if (kind === 'video') {
- const frames = await videoFrameExtractor.extract(file);
- if (frames.length === 0) {
- return { error: { code: 'read_failed', reason: 'no frames extracted' } };
- }
- return {
- attachment: {
- id: globalThis.crypto.randomUUID(),
- kind: 'video',
- file,
- // The clip is represented to the agent by its frames, not a data URI;
- // the poster (first frame) drives the chip thumbnail.
- dataUri: frames[0],
- previewUri: frames[0],
- mimeType: file.type,
- originalSizeBytes: file.size,
- payloadSizeBytes: file.size,
- compressed: false,
- frames,
- },
- };
- }
-
- const { dataUri, payloadSizeBytes, compressed } = await buildAttachmentDataUri(file, file.type);
+ const { dataUri, payloadSizeBytes, compressed } = await buildAttachmentDataUri(file, mimeType);
const previewUri = kind === 'image' ? await fileToDataUri(file) : undefined;
return {
attachment: {
@@ -388,7 +293,7 @@ export async function validateAndReadFile(
file,
dataUri,
previewUri,
- mimeType: file.type,
+ mimeType,
originalSizeBytes: file.size,
payloadSizeBytes,
compressed,
@@ -410,13 +315,7 @@ export async function validateAndReadFile(
export function buildMessageWithAttachments(text: string, attachments: Attachment[]): string {
if (attachments.length === 0) return text;
const markers = attachments
- .map(a => {
- if (a.kind === 'image') return `[IMAGE:${a.dataUri}]`;
- if (a.kind === 'file') return `[FILE:${a.dataUri}]`;
- // Video: forward each sampled still as its own image marker so the agent
- // "sees" the clip through the existing vision path.
- return (a.frames ?? []).map(frame => `[IMAGE:${frame}]`).join(' ');
- })
+ .map(a => `[${a.kind === 'image' ? 'IMAGE' : 'FILE'}:${a.dataUri}]`)
.filter(marker => marker.length > 0)
.join(' ');
return text.trim() ? `${text.trim()} ${markers}` : markers;
diff --git a/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts b/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts
index b230ff53e4..1a766a8048 100644
--- a/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts
+++ b/app/test/playwright/specs/chat-composer-attachment-gate.spec.ts
@@ -179,6 +179,21 @@ test.describe('Chat composer attachment gate', () => {
await expect(page.getByText('picker-notes.txt')).toBeVisible();
});
+ test('the picker accepts archive, audio, unknown and original video files', async ({ page }) => {
+ await openChat(page);
+ for (const [name, mimeType] of [
+ ['archive.zip', 'application/zip'],
+ ['voice.mp3', 'audio/mpeg'],
+ ['opaque.bin', ''],
+ ['undecodable.mp4', 'video/mp4'],
+ ]) {
+ await fileInput(page)
+ .first()
+ .setInputFiles({ name, mimeType, buffer: Buffer.from([0, 255, 128]) });
+ await expect(page.getByText(name)).toBeVisible();
+ }
+ });
+
test('an attached file can be removed again', async ({ page }) => {
await openChat(page);
await attach(page, 'removable.txt');