Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.7.3: drop videos into a chat (frontend P1–P4) (#372)

Oleksandr Ivanchenko6bffab6672c6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 405fe07e..11057e8a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,7 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- **Dev mode reads any git repo.** Repos on GitLab, Gitea or any git server, and team folders with no remote, are watched with git, and what lands there shows on the Dev desk. Reviews, CI checks and Post to GitHub still work on GitHub repos only. The server needs git 2.31 or newer; without it, the desk says "Needs git on the server". (#366, #368)
- **Connect GitHub in one place.** Every Connect GitHub (the Dev desk's status line and empty state, the Dev mode toast, Dev mode setup and Team settings) opens the same GitHub form right where you pressed it: a popover on the desktop, a sheet on the phone. It no longer jumps to Loose ends. The GitHub row in Loose ends says "Also used by Dev mode".
- **Team settings say what Dev mode does with the repo.** Under Git Repo URL, one line: watched with GitHub connected, watched but needs Connect GitHub for reviews, can be watched once Dev mode is on, or read with git (reviews need GitHub).
-- **Videos in chat.** MP4, MOV and WebM files up to 100 MB can be attached and shared by bots (other files stay at 20 MB), and they play right in the chat. The type comes from the file's bytes, not its name. A file kwant can't take is refused right after its first bytes instead of after the whole upload. With ffmpeg on the server, a bot reading a video gets its length and size and up to 6 frames; without ffmpeg it is told to install it.
+- **Videos in chat, without the wait.** MP4, MOV and WebM files up to 100 MB can be attached and shared by bots (other files stay at 20 MB), and they play right in the chat (no autoplay), falling back to the file card when the browser can't play them. The type comes from the file's bytes, not its name. A file kwant can't take is refused the moment it's dropped, with one line naming what works; anything that gets past the browser is refused by the server right after its first bytes instead of after the whole upload. A dropped connection or a 502/503/504 retries by itself twice (after 1 s, then 3 s) before showing Retry. Upload chips show "5.2 of 8.0 MB". With ffmpeg on the server, a bot reading a video gets its length and size and up to 6 frames; without ffmpeg it is told to install it. (#372, #373)
### Changed
- **Dev mode reads commit history with git, not GitHub's API.** Each watched repo gets a copy in kwant's data folder, up to 1 GB each; a bigger repo reads "Too big to read". Repo addresses that point at this server, link-local addresses or cloud metadata addresses are refused, and https reads are pinned to the address that was checked. A team folder whose .git points somewhere else is refused. GitHub PRs, checks and logins still come from GitHub. (#366)
diff --git a/frontend/src/attachments.ts b/frontend/src/attachments.ts
index 936d7d90..c2d0a674 100644
--- a/frontend/src/attachments.ts
+++ b/frontend/src/attachments.ts
@@ -2,6 +2,8 @@
import { parseMetaObject } from './questions';
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
+/** Videos (mp4, mov, webm) may be bigger; the server enforces the same caps by the file's bytes. */
+export const MAX_VIDEO_BYTES = 100 * 1024 * 1024;
export const MAX_ATTACHMENTS = 10;
/** What a message's `meta.attachments` holds. */
@@ -28,6 +30,9 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
/** Only these render inline (the server serves everything else as a download). */
export const isInlineImage = (mime: string) => INLINE_IMAGES.has(mime.toLowerCase());
+/** Sent videos the chat tries to play (P2); a browser that can't falls back to the file card. */
+export const isVideo = (mime: string | undefined) => VIDEO_MIMES.has((mime || '').toLowerCase().split(';')[0].trim());
+
export const attachmentUrl = (id: string, download = false) =>
`/api/attachments/${encodeURIComponent(id)}/content${download ? '?download=1' : ''}`;
@@ -43,6 +48,9 @@ export function fileKind(mime: string, name: string): string {
const m = mime.toLowerCase();
if (m === 'application/pdf') return 'PDF';
if (m.startsWith('image/')) return m.slice(6).toUpperCase().replace('JPEG', 'JPG');
+ if (m === 'video/quicktime') return 'MOV';
+ if (m === 'video/mp4') return 'MP4';
+ if (m === 'video/webm') return 'WebM';
if (m === 'application/json') return 'JSON';
if (m === 'text/csv') return 'CSV';
if (m === 'text/markdown') return 'Markdown';
@@ -65,10 +73,87 @@ export function parseAttachments(meta: unknown): AttachmentRef[] {
/** An agent's `share_file` message: the file tiles stand in for the text. */
export const isSharedFileMessage = (meta: unknown) => parseMetaObject(meta)?.kind === 'file';
-/** Checked before uploading, so a too-big file never leaves the browser. */
-export function preflightFile(f: { name: string; size: number }): string | null {
- if (f.size === 0) return `${f.name || 'That file'} is empty.`;
- if (f.size > MAX_ATTACHMENT_BYTES) return `${f.name || 'That file'} is too big (${(f.size / (1024 * 1024)).toFixed(1)} MB). Max 20 MB.`;
+// ---------------------------------------------------------------------------
+// What can be attached: checked in the browser so an unsupported file never uploads (0.7.3, P1).
+// The server still decides by the file's bytes; this only refuses what it would refuse anyway.
+
+const IMAGE_MIMES = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp']);
+const VIDEO_MIMES = new Set(['video/mp4', 'video/quicktime', 'video/webm']);
+const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp']);
+const VIDEO_EXTS = new Set(['mp4', 'm4v', 'mov', 'webm']);
+/** Text and code: the server keeps these when the bytes are UTF-8. */
+const TEXT_EXTS = new Set(
+ (
+ 'txt text md markdown csv tsv json jsonl ndjson log yaml yml toml ini cfg conf env xml html htm css scss sass less svg ' +
+ 'js mjs cjs jsx ts tsx mts cts vue svelte astro py pyi rb php java kt kts scala go rs c h cc cpp cxx hpp hh m mm swift ' +
+ 'cs fs vb lua pl pm r jl dart ex exs erl hs ml clj sql sh bash zsh fish ps1 bat cmd make mk cmake gradle properties ' +
+ 'gitignore gitattributes editorconfig dockerfile lock patch diff tex bib rst adoc org srt vtt'
+ ).split(' '),
+);
+/**
+ * Known binary formats kwant can't keep: refused in the browser. Not `key`: server.key is PEM text,
+ * and a Keynote .key gets the server's 415 anyway.
+ */
+const BINARY_EXTS = new Set(
+ (
+ 'zip 7z rar gz tgz bz2 xz zst tar iso dmg pkg exe msi dll so dylib apk ipa jar class wasm bin ' +
+ 'heic heif avif tif tiff bmp ico psd mp3 wav m4a aac flac ogg opus aiff mkv avi wmv flv mpg mpeg 3gp ' +
+ 'doc docx xls xlsx ppt pptx odt ods odp pages numbers sqlite woff woff2 ttf otf eot'
+ ).split(' '),
+);
+const BINARY_MIMES = new Set(
+ (
+ 'application/zip application/x-zip-compressed application/gzip application/x-gzip application/x-tar ' +
+ 'application/x-7z-compressed application/x-rar-compressed application/vnd.rar application/x-bzip2 application/x-xz ' +
+ 'application/x-msdownload application/x-msdos-program application/x-apple-diskimage application/x-iso9660-image ' +
+ 'application/java-archive application/vnd.android.package-archive application/msword'
+ ).split(' '),
+);
+const BINARY_MIME_PREFIXES = ['audio/', 'font/', 'image/', 'video/', 'application/vnd.ms-', 'application/vnd.openxmlformats-officedocument.', 'application/vnd.oasis.opendocument.'];
+const isBinaryMime = (mime: string) => BINARY_MIMES.has(mime) || BINARY_MIME_PREFIXES.some((p) => mime.startsWith(p));
+
+const extOf = (name: string) => /\.([a-z0-9]{1,12})$/i.exec(name)?.[1]?.toLowerCase() ?? '';
+
+export type AttachKind = 'image' | 'pdf' | 'text' | 'video';
+
+/**
+ * What kind of file this is, or null when kwant surely can't take it. Extension first: browsers call
+ * `.ts` "video/mp2t". Only known binary formats are refused here; anything else goes up as text and
+ * the server's byte check decides (a binary file gets a 415 within its first bytes).
+ */
+export function attachKind(f: { name: string; type?: string }): AttachKind | null {
+ const mime = (f.type || '').toLowerCase().split(';')[0].trim();
+ const ext = extOf((f.name || '').toLowerCase());
+ if (TEXT_EXTS.has(ext)) return 'text';
+ if (IMAGE_EXTS.has(ext)) return 'image';
+ if (VIDEO_EXTS.has(ext)) return 'video';
+ if (ext === 'pdf') return 'pdf';
+ if (BINARY_EXTS.has(ext)) return null;
+ if (IMAGE_MIMES.has(mime)) return 'image';
+ if (VIDEO_MIMES.has(mime)) return 'video';
+ if (mime === 'application/pdf') return 'pdf';
+ if (mime.startsWith('text/') || mime === 'application/json') return 'text';
+ if (isBinaryMime(mime)) return null;
+ // An unknown extension or none (server.key, main.tf, a Makefile, a pasted snippet): let the server look.
+ return 'text';
+}
+
+/** The one line shown when a file's type can't be attached. */
+export const SUPPORTED_TYPES_TEXT = 'Images, videos (MP4, MOV, WebM), PDFs and text or code files work.';
+
+export const capFor = (kind: AttachKind | null) => (kind === 'video' ? MAX_VIDEO_BYTES : MAX_ATTACHMENT_BYTES);
+
+/** Checked before uploading, so an unsupported or too-big file never leaves the browser. */
+export function preflightFile(f: { name: string; size: number; type?: string }): string | null {
+ const label = f.name || 'That file';
+ const kind = attachKind(f);
+ if (!kind) return `${label} can't be attached. ${SUPPORTED_TYPES_TEXT}`;
+ if (f.size === 0) return `${label} is empty.`;
+ const cap = capFor(kind);
+ if (f.size > cap) {
+ const mb = (f.size / (1024 * 1024)).toFixed(1);
+ return kind === 'video' ? `${label} is too big (${mb} MB). Videos can be up to 100 MB.` : `${label} is too big (${mb} MB). Max 20 MB (videos 100 MB).`;
+ }
return null;
}
@@ -76,9 +161,9 @@ export function preflightFile(f: { name: string; size: number }): string | null
export function uploadErrorText(status: number, serverMessage?: string): string {
switch (status) {
case 413:
- return 'Too big. Max 20 MB.';
+ return serverMessage || 'Too big. Max 20 MB, videos 100 MB.';
case 415:
- return "That file type isn't supported. Images, PDFs and text files work.";
+ return `That file type isn't supported. ${SUPPORTED_TYPES_TEXT}`;
case 400:
return serverMessage || 'The file is empty or its name is not allowed.';
case 401:
@@ -86,17 +171,32 @@ export function uploadErrorText(status: number, serverMessage?: string): string
return 'Your session ended. Sign in again.';
case 0:
return 'Upload interrupted. Check the connection and retry.';
+ case 502:
+ case 503:
+ case 504:
+ return "The server didn't answer in time. Retry in a moment.";
default:
return serverMessage || `Upload failed (HTTP ${status}).`;
}
}
-/** Whether retrying the same file can help: not when the server refused the file itself. */
-export const uploadRetryable = (status: number) => status !== 400 && status !== 413 && status !== 415;
+/**
+ * Whether retrying the same file can help: not when the server refused the file itself. A 400 whose
+ * `code` is `interrupted` (the body stream broke on the way) is a blip, not a refusal.
+ */
+export const uploadRetryable = (status: number, code?: string) => (status === 400 ? code === 'interrupted' : status !== 413 && status !== 415);
+
+/** A network blip or a gateway hiccup: retried by itself, without the person pressing Retry (P3). */
+export const uploadAutoRetryable = (status: number, code?: string) =>
+ status === 0 || status === 502 || status === 503 || status === 504 || (status === 400 && code === 'interrupted');
+
+/** Waits before the first and second automatic retry. */
+export const AUTO_RETRY_DELAYS_MS = [1000, 3000] as const;
/** An upload the server refused, or that never reached it (`status` 0). */
export class UploadError extends Error {
- constructor(readonly status: number, serverMessage?: string) {
+ /** The server's stable error `code` (`too_large`, `unsupported_type`, `empty`, `interrupted`), when it sent one. */
+ constructor(readonly status: number, serverMessage?: string, readonly code?: string) {
super(uploadErrorText(status, serverMessage));
}
}
@@ -117,9 +217,13 @@ export interface PendingUpload {
key: string;
name: string;
size: number;
+ /** The browser's MIME type, for the chip's icon. */
+ mime?: string;
/** 0–1 */
progress: number;
state: UploadState;
+ /** True while waiting to retry by itself after a blip. */
+ retrying?: boolean;
error?: string;
/** False when Retry can't help, e.g. an unsupported file type. */
retryable?: boolean;
@@ -160,8 +264,8 @@ export function uploadAttachment(file: Blob & { name?: string }, onProgress: (fr
onProgress(1);
resolve(body as Attachment);
} else {
- const msg = body && typeof (body as { error?: unknown }).error === 'string' ? (body as { error: string }).error : undefined;
- reject(new UploadError(xhr.status, msg));
+ const b = (body && typeof body === 'object' ? body : {}) as { error?: unknown; code?: unknown };
+ reject(new UploadError(xhr.status, typeof b.error === 'string' ? b.error : undefined, typeof b.code === 'string' ? b.code : undefined));
}
};
xhr.onerror = () => reject(new UploadError(0));
@@ -171,6 +275,64 @@ export function uploadAttachment(file: Blob & { name?: string }, onProgress: (fr
});
}
+/** "5.2 of 8.0 MB" for a chip while it uploads (P4); KB for small files. */
+export function uploadProgressText(fraction: number, size: number): string {
+ const f = Number.isFinite(fraction) ? Math.min(1, Math.max(0, fraction)) : 0;
+ if (!Number.isFinite(size) || size <= 0) return `${Math.round(f * 100)}%`;
+ const MB = 1024 * 1024;
+ if (size >= MB) return `${((f * size) / MB).toFixed(1)} of ${(size / MB).toFixed(1)} MB`;
+ return `${Math.round((f * size) / 1024)} of ${Math.max(1, Math.round(size / 1024))} KB`;
+}
+
+const sleep = (ms: number, signal?: AbortSignal) =>
+ new Promise<void>((resolve, reject) => {
+ if (signal?.aborted) return reject(new DOMException('Upload cancelled', 'AbortError'));
+ const t = setTimeout(() => {
+ signal?.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+ const onAbort = () => {
+ clearTimeout(t);
+ reject(new DOMException('Upload cancelled', 'AbortError'));
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ });
+
+export interface RetryOptions {
+ /** Called before each automatic retry (attempt 1 or 2), so the chip can say "Retrying…". */
+ onRetrying?: (attempt: number) => void;
+ delays?: readonly number[];
+ /** For tests. */
+ upload?: typeof uploadAttachment;
+ wait?: (ms: number, signal?: AbortSignal) => Promise<void>;
+}
+
+/**
+ * `uploadAttachment`, retried by itself after a dropped connection or a 502/503/504: twice, after
+ * 1 s and then 3 s. A refusal (413, 415, 400) or anything else fails at once, as before.
+ */
+export async function uploadWithRetry(
+ file: Blob & { name?: string },
+ onProgress: (fraction: number) => void,
+ signal?: AbortSignal,
+ opts: RetryOptions = {},
+): Promise<Attachment> {
+ const delays = opts.delays ?? AUTO_RETRY_DELAYS_MS;
+ const upload = opts.upload ?? uploadAttachment;
+ const wait = opts.wait ?? sleep;
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await upload(file, onProgress, signal);
+ } catch (err) {
+ const blip = err instanceof UploadError && uploadAutoRetryable(err.status, err.code);
+ if (!blip || attempt >= delays.length || signal?.aborted) throw err;
+ opts.onRetrying?.(attempt + 1);
+ await wait(delays[attempt], signal);
+ onProgress(0);
+ }
+ }
+}
+
/** Files from a paste or drop (ignores plain text and dragged links). */
export function filesFrom(list: DataTransferItemList | FileList | null | undefined): File[] {
if (!list) return [];
diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx
index f9b94f92..bf00d255 100644
--- a/frontend/src/components/Attachments.tsx
+++ b/frontend/src/components/Attachments.tsx
@@ -1,6 +1,6 @@
import React, { useState } from 'react';
-import { AlertCircle, Download, FileText, Loader2, RotateCw, X } from 'lucide-react';
-import { AttachmentRef, PendingUpload, attachmentUrl, fileKind, formatBytes, isInlineImage } from '../attachments';
+import { AlertCircle, Download, FileText, Film, Loader2, RotateCw, X } from 'lucide-react';
+import { AttachmentRef, PendingUpload, attachKind, attachmentUrl, fileKind, formatBytes, isInlineImage, isVideo, uploadProgressText } from '../attachments';
/**
* A file on a message: images as a thumbnail (opens full size), everything else as a tile.
@@ -9,6 +9,7 @@ import { AttachmentRef, PendingUpload, attachmentUrl, fileKind, formatBytes, isI
export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
const [broken, setBroken] = useState(false);
const image = isInlineImage(file.mime) && !broken;
+ const video = isVideo(file.mime) && !broken;
const download = (
<a
href={attachmentUrl(file.id, true)}
@@ -51,10 +52,31 @@ export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
</figure>
);
}
+ if (video) {
+ // P2: a player for sent videos. No autoplay; only the metadata loads until Play. A browser that
+ // can't decode it (some .mov in Chrome) errors and falls back to the file card below.
+ return (
+ <figure className="w-full sm:w-80 max-w-full rounded-xl overflow-hidden border border-zinc-800 bg-zinc-900/80">
+ <video
+ src={attachmentUrl(file.id)}
+ controls
+ preload="metadata"
+ playsInline
+ aria-label={file.name}
+ onError={() => setBroken(true)}
+ className="block w-full max-h-72 bg-black"
+ />
+ <figcaption className="flex items-center gap-2 px-2.5 py-1.5">
+ {label}
+ {download}
+ </figcaption>
+ </figure>
+ );
+ }
return (
<div className="flex items-center gap-2.5 w-full sm:w-72 max-w-full px-2.5 py-2 rounded-xl border border-zinc-800 bg-zinc-900/80">
<span className="w-8 h-8 shrink-0 rounded-lg bg-zinc-800 border border-zinc-700/60 flex items-center justify-center text-zinc-400" aria-hidden="true">
- <FileText size={15} />
+ {isVideo(file.mime) ? <Film size={15} /> : <FileText size={15} />}
</span>
{label}
{download}
@@ -76,6 +98,7 @@ export const FileTiles: React.FC<{ files: AttachmentRef[]; align?: 'start' | 'en
export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; onRetry?: () => void }> = ({ item, onRemove, onRetry }) => {
const pct = Math.round(item.progress * 100);
const failed = item.state === 'error';
+ const video = isVideo(item.mime || item.attachment?.mime) || attachKind({ name: item.name, type: item.mime }) === 'video';
return (
<li
className={`relative flex items-center gap-2 max-w-full sm:max-w-[16rem] pl-2 pr-1 py-1 rounded-lg border text-[11px] overflow-hidden ${
@@ -86,6 +109,8 @@ export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; o
<Loader2 size={12} className="shrink-0 text-sky-300 animate-spin motion-reduce:animate-none" aria-hidden="true" />
) : failed ? (
<AlertCircle size={12} className="shrink-0 text-rose-300" aria-hidden="true" />
+ ) : video ? (
+ <Film size={12} className="shrink-0 text-zinc-400" aria-hidden="true" />
) : (
<FileText size={12} className="shrink-0 text-zinc-400" aria-hidden="true" />
)}
@@ -94,7 +119,7 @@ export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; o
{item.name}
</span>
<span className={`block ${failed ? 'text-rose-300 break-words' : 'truncate text-zinc-500'}`} role={failed ? 'alert' : undefined}>
- {failed ? item.error : item.state === 'uploading' ? `Uploading… ${pct}%` : formatBytes(item.size)}
+ {failed ? item.error : item.state === 'uploading' ? (item.retrying ? 'Retrying…' : uploadProgressText(item.progress, item.size)) : formatBytes(item.size)}
</span>
</span>
{failed && onRetry && item.retryable !== false && (
@@ -121,6 +146,7 @@ export const UploadChip: React.FC<{ item: PendingUpload; onRemove: () => void; o
style={{ width: `${pct}%` }}
role="progressbar"
aria-label={`Uploading ${item.name}`}
+ aria-valuetext={item.retrying ? 'Retrying' : uploadProgressText(item.progress, item.size)}
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={pct}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 02d0ed0a..a66ae908 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -38,7 +38,7 @@ import {
parseAttachments,
preflightFile,
readyAttachments,
- uploadAttachment,
+ uploadWithRetry,
uploadRetryable,
uploadSlotsLeft,
} from '../attachments';
@@ -806,12 +806,14 @@ export const ChatView: React.FC<ChatViewProps> = ({
const startUpload = (key: string, file: File) => {
const abort = new AbortController();
uploadFiles.current.set(key, { file, abort });
- uploadAttachment(file, (progress) => patchUpload(key, { progress }), abort.signal).then(
- (attachment) => patchUpload(key, { state: 'done', progress: 1, attachment, error: undefined }),
+ uploadWithRetry(file, (progress) => patchUpload(key, { progress, retrying: false }), abort.signal, {
+ onRetrying: () => patchUpload(key, { retrying: true, progress: 0 }),
+ }).then(
+ (attachment) => patchUpload(key, { state: 'done', progress: 1, attachment, error: undefined, retrying: false }),
(err: Error) => {
if (err.name === 'AbortError') return;
- const retryable = !(err instanceof UploadError) || uploadRetryable(err.status);
- patchUpload(key, { state: 'error', error: err.message, retryable });
+ const retryable = !(err instanceof UploadError) || uploadRetryable(err.status, err.code);
+ patchUpload(key, { state: 'error', error: err.message, retryable, retrying: false });
},
);
};
@@ -830,7 +832,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
continue;
}
const key = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
- added.push({ key, name: file.name || 'pasted file', size: file.size, progress: 0, state: 'uploading' });
+ added.push({ key, name: file.name || 'pasted file', size: file.size, mime: file.type || undefined, progress: 0, state: 'uploading' });
startUpload(key, file);
}
setUploadNote(notes.length ? notes.join(' ') : null);
@@ -1966,7 +1968,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={uploadSlotsLeft(uploads) === 0}
- title={uploadSlotsLeft(uploads) === 0 ? `Up to ${MAX_ATTACHMENTS} files per message` : 'Attach files (or drop / paste them here). Max 20 MB each.'}
+ title={uploadSlotsLeft(uploads) === 0 ? `Up to ${MAX_ATTACHMENTS} files per message` : 'Attach files (or drop / paste them here). Max 20 MB each, videos 100 MB.'}
aria-label="Attach files"
className={`${phone ? toolPhone : 'w-11 h-11 sm:w-9 sm:h-9 text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08] focus-visible:outline-sky-400'} rounded-xl flex items-center justify-center flex-shrink-0 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:outline focus-visible:outline-2`}
>
diff --git a/frontend/tests/attachments.test.mjs b/frontend/tests/attachments.test.mjs
index abc2676b..6d80fca4 100644
--- a/frontend/tests/attachments.test.mjs
+++ b/frontend/tests/attachments.test.mjs
@@ -17,12 +17,12 @@ const MB = 1024 * 1024;
test('the 20 MB limit and empty files are caught before upload', () => {
assert.equal(a.preflightFile({ name: 'ok.pdf', size: 20 * MB }), null);
- assert.match(a.preflightFile({ name: 'big.mov', size: 20 * MB + 1 }), /big\.mov is too big \(20\.0 MB\)\. Max 20 MB\./);
+ assert.match(a.preflightFile({ name: 'big.pdf', size: 20 * MB + 1 }), /big\.pdf is too big \(20\.0 MB\)\. Max 20 MB/);
assert.match(a.preflightFile({ name: 'e.txt', size: 0 }), /empty/);
});
test('server refusals read as plain language', () => {
- assert.match(a.uploadErrorText(413), /Max 20 MB/);
+ assert.match(a.uploadErrorText(413), /Max 20 MB, videos 100 MB/);
assert.match(a.uploadErrorText(415), /isn't supported/);
assert.equal(a.uploadErrorText(400, 'bad name'), 'bad name');
assert.match(a.uploadErrorText(0), /interrupted/);
@@ -30,6 +30,7 @@ test('server refusals read as plain language', () => {
// Retry can't help when the server refused the file itself
for (const st of [400, 413, 415]) assert.equal(a.uploadRetryable(st), false, `HTTP ${st}`);
for (const st of [0, 401, 429, 500, 503]) assert.equal(a.uploadRetryable(st), true, `HTTP ${st}`);
+ assert.match(a.uploadErrorText(415), /videos \(MP4, MOV, WebM\)/);
const e = new a.UploadError(415);
assert.equal(e.status, 415);
assert.match(e.message, /isn't supported/);
@@ -95,7 +96,7 @@ test('upload chips show progress, and failures with the reason', () => {
const uploading = ui.chip({ key: 'k', name: 'b.pdf', size: 10, progress: 0.42, state: 'uploading' });
assert.match(uploading, /role="progressbar"/);
assert.match(uploading, /aria-valuenow="42"/);
- assert.match(uploading, /Uploading… 42%/);
+ assert.match(uploading, /4 of 10 B|0 of 1 KB/);
assert.match(uploading, /Cancel uploading b.pdf/);
const failed = ui.chip({ key: 'k', name: 'c.exe', size: 10, progress: 0, state: 'error', error: 'Not supported' });
assert.match(failed, /role="alert">Not supported/);
@@ -104,3 +105,215 @@ test('upload chips show progress, and failures with the reason', () => {
assert.match(refused, /role="alert">Not supported/);
assert.doesNotMatch(refused, /Retry/);
});
+
+
+// --- 0.7.3 video drop: P1 type table, P2 player and fallback, P3 auto-retry, P4 MB progress ---
+
+test('P1: supported types pass, everything else is refused before upload', () => {
+ const ok = [
+ ['clip.mp4', 'video/mp4'], ['clip.MOV', 'video/quicktime'], ['clip.webm', 'video/webm'], ['clip.m4v', ''],
+ ['phone.mov', ''], ['noext', 'video/mp4'],
+ ['cat.png', 'image/png'], ['a.JPG', ''], ['b.gif', 'image/gif'], ['c.webp', 'image/webp'],
+ ['doc.pdf', 'application/pdf'], ['doc', 'application/pdf'],
+ ['notes.txt', 'text/plain'], ['r.md', ''], ['d.csv', 'text/csv'], ['x.json', 'application/json'],
+ ['main.ts', 'video/mp2t'], ['App.tsx', ''], ['lib.rs', ''], ['run.py', 'text/x-python'], ['Makefile', ''], ['pasted', ''],
+ ];
+ for (const [name, type] of ok) assert.equal(a.preflightFile({ name, type, size: 1000 }), null, `${name} (${type || 'no type'})`);
+ // F1: text files with an extension we don't list still go up as text; the server's byte check decides.
+ const unlisted = [
+ ['server.key', ''], ['cert.pem', 'application/x-x509-ca-cert'], ['api.proto', 'application/octet-stream'], ['main.tf', ''],
+ ['schema.graphql', ''], ['.env.local', ''], ['build.zig', 'application/octet-stream'], ['flake.nix', ''], ['app.csproj', ''],
+ ['tsconfig.jsonc', ''], ['page.mdx', ''], ['Token.sol', 'application/octet-stream'], ['build.groovy', ''],
+ ];
+ for (const [name, type] of unlisted) {
+ assert.equal(a.attachKind({ name, type }), 'text', `${name} (${type || 'no type'})`);
+ assert.equal(a.preflightFile({ name, type, size: 1000 }), null, name);
+ }
+ assert.match(a.preflightFile({ name: 'main.tf', type: '', size: 21 * MB }), /Max 20 MB/);
+ const refused = [
+ ['a.zip', 'application/zip'], ['setup.exe', 'application/x-msdownload'], ['r.docx', ''], ['photo.heic', 'image/heic'],
+ ['song.mp3', 'audio/mpeg'], ['film.mkv', 'video/x-matroska'], ['clip.avi', 'video/x-msvideo'], ['x.bin', 'application/octet-stream'],
+ ['noext', 'application/zip'],
+ // a binary mime on an unknown extension, and a known binary extension with no mime
+ ['data.foo', 'application/zip'], ['installer.dmg', ''], ['tune.xyz', 'audio/ogg'], ['deck.abc', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'],
+ ];
+ for (const [name, type] of refused) {
+ const why = a.preflightFile({ name, type, size: 1000 });
+ assert.ok(why, `${name} should be refused`);
+ assert.match(why, /can't be attached\. Images, videos \(MP4, MOV, WebM\), PDFs and text or code files work\./);
+ }
+ assert.equal(a.attachKind({ name: 'main.ts', type: 'video/mp2t' }), 'text');
+ assert.equal(a.attachKind({ name: 'v.mov', type: 'video/quicktime' }), 'video');
+ assert.equal(a.attachKind({ name: 'data.foo', type: 'application/zip' }), null);
+ assert.equal(a.attachKind({ name: 'installer.dmg', type: '' }), null);
+});
+
+test('P1: videos may be 100 MB, everything else 20 MB', () => {
+ assert.equal(a.preflightFile({ name: 'v.mp4', type: 'video/mp4', size: 100 * MB }), null);
+ assert.match(a.preflightFile({ name: 'v.mp4', type: 'video/mp4', size: 120 * MB }), /v\.mp4 is too big \(120\.0 MB\)\. Videos can be up to 100 MB\./);
+ assert.match(a.preflightFile({ name: 'p.png', type: 'image/png', size: 21 * MB }), /Max 20 MB \(videos 100 MB\)/);
+ assert.match(a.preflightFile({ name: 'v.webm', type: 'video/webm', size: 0 }), /empty/);
+ // the type is checked first: a huge zip says the type, not the size
+ assert.match(a.preflightFile({ name: 'big.zip', type: 'application/zip', size: 500 * MB }), /can't be attached/);
+ assert.match(a.preflightFile({ name: 'data.csv', type: 'text/csv', size: 25 * MB }), /data\.csv is too big \(25\.0 MB\)\. Max 20 MB/);
+});
+
+test('P4: chips show uploaded MB of total', () => {
+ assert.equal(a.uploadProgressText(0.65, 8 * MB), '5.2 of 8.0 MB');
+ assert.equal(a.uploadProgressText(0, 8 * MB), '0.0 of 8.0 MB');
+ assert.equal(a.uploadProgressText(1.5, 8 * MB), '8.0 of 8.0 MB');
+ assert.equal(a.uploadProgressText(0.5, 300 * 1024), '150 of 300 KB');
+ const chip = ui.chip({ key: 'k', name: 'clip.mp4', mime: 'video/mp4', size: 8 * MB, progress: 0.65, state: 'uploading' });
+ assert.match(chip, /5\.2 of 8\.0 MB/);
+ assert.match(chip, /aria-valuetext="5\.2 of 8\.0 MB"/);
+ const retrying = ui.chip({ key: 'k', name: 'clip.mp4', mime: 'video/mp4', size: 8 * MB, progress: 0, state: 'uploading', retrying: true });
+ assert.match(retrying, /Retrying…/);
+});
+
+test('P2: a sent video is a player with no autoplay; other files keep their card', () => {
+ const html = ui.tiles([
+ { id: ID, name: 'clip.mp4', mime: 'video/mp4', size: 8 * MB },
+ { id: ID2, name: 'report.pdf', mime: 'application/pdf', size: MB },
+ ]);
+ assert.match(html, new RegExp(`<video src="/api/attachments/${ID}/content" controls="" preload="metadata" playsinline=""`));
+ assert.doesNotMatch(html, /autoplay/i);
+ assert.match(html, /aria-label="Download clip.mp4"/);
+ assert.match(html, /MP4 · 8\.0 MB/);
+ assert.doesNotMatch(html, new RegExp(`<video[^>]*${ID2}`));
+ assert.equal(a.isVideo('video/quicktime'), true);
+ assert.equal(a.isVideo('video/x-matroska'), false);
+ // composer chip: a film icon for a finished video, a file icon otherwise
+ const done = ui.chip({ key: 'k', name: 'clip.mov', size: 8 * MB, progress: 1, state: 'done' });
+ assert.match(done, /lucide-film/);
+ assert.doesNotMatch(ui.chip({ key: 'k', name: 'a.pdf', size: 1, progress: 1, state: 'done' }), /lucide-film/);
+});
+
+test('P2: a video the browser cannot play falls back to the file card', async () => {
+ const { JSDOM } = await import('jsdom');
+ const dom = new JSDOM('<!doctype html><div id="root"></div>', { pretendToBeVisual: true });
+ const g = globalThis;
+ const saved = { window: g.window, document: g.document };
+ g.window = dom.window;
+ g.document = dom.window.document;
+ try {
+ const live = await loadBundled(`
+ import React from 'react';
+ import { createRoot } from 'react-dom/client';
+ import { FileTiles } from './src/components/Attachments';
+ export function mount(el, files) { const r = createRoot(el); r.render(React.createElement(FileTiles, { files })); return r; }
+ `);
+ const el = dom.window.document.getElementById('root');
+ const settle = async () => { for (let i = 0; i < 10; i++) await new Promise((r) => setTimeout(r, 0)); };
+ const root = live.mount(el, [{ id: ID, name: 'phone.mov', mime: 'video/quicktime', size: 8 * MB }]);
+ await settle();
+ const video = el.querySelector('video');
+ assert.ok(video, 'starts as a player');
+ video.dispatchEvent(new dom.window.Event('error'));
+ await settle();
+ assert.equal(el.querySelector('video'), null, 'player gone after a decode error');
+ assert.match(el.textContent, /phone\.mov/);
+ assert.match(el.textContent, /MOV · 8\.0 MB/);
+ assert.ok(el.querySelector('a[aria-label="Download phone.mov"]'), 'download stays');
+ root.unmount();
+ } finally {
+ g.window = saved.window;
+ g.document = saved.document;
+ }
+});
+
+// A fake XMLHttpRequest that answers each request from a script: a status, or 'drop' for a lost connection.
+function installFakeXhr(script) {
+ const sent = [];
+ class FakeXHR {
+ constructor() { this.upload = {}; this.status = 0; this.responseText = ''; }
+ open(method, url) { this.method = method; this.url = url; }
+ abort() { this.onabort?.(); }
+ send(body) {
+ sent.push({ url: this.url, size: body?.size });
+ const step = script.shift() ?? 201;
+ queueMicrotask(() => {
+ this.upload.onprogress?.({ lengthComputable: true, loaded: 4, total: 8 });
+ if (step === 'drop') return this.onerror?.();
+ this.status = step;
+ const code = { 413: 'too_large', 415: 'unsupported_type', 400: 'empty' }[step];
+ this.responseText = step === 201 ? JSON.stringify({ id: ID, name: 'clip.mp4', mime: 'video/mp4', size: 8 })
+ : step === 'interrupted' ? JSON.stringify({ error: 'The upload was interrupted.', code: 'interrupted' })
+ : JSON.stringify({ error: `HTTP ${step}`, code });
+ if (step === 'interrupted') this.status = 400;
+ this.onload?.();
+ });
+ }
+ }
+ const prev = globalThis.XMLHttpRequest;
+ globalThis.XMLHttpRequest = FakeXHR;
+ return { sent, restore: () => { globalThis.XMLHttpRequest = prev; } };
+}
+
+async function runUpload(script) {
+ const fake = installFakeXhr(script);
+ const waits = [];
+ const retries = [];
+ const progress = [];
+ try {
+ const file = Object.assign(new Blob([new Uint8Array(8)]), { name: 'clip.mp4' });
+ const result = await a
+ .uploadWithRetry(file, (f) => progress.push(f), undefined, { onRetrying: (n) => retries.push(n), wait: async (ms) => { waits.push(ms); } })
+ .then((v) => ({ ok: v }), (e) => ({ err: e }));
+ return { ...result, waits, retries, progress, sent: fake.sent.length };
+ } finally {
+ fake.restore();
+ }
+}
+
+test('P3: a dropped connection or 502/503/504 retries by itself, after 1 s then 3 s', async () => {
+ for (const blip of ['drop', 502, 503, 504, 'interrupted']) {
+ const r = await runUpload([blip, 201]);
+ assert.equal(r.ok?.id, ID, `${blip} then success`);
+ assert.deepEqual(r.waits, [1000], `${blip}: one wait of 1 s`);
+ assert.deepEqual(r.retries, [1]);
+ assert.equal(r.sent, 2);
+ }
+ const twice = await runUpload(['drop', 503, 201]);
+ assert.equal(twice.ok?.id, ID);
+ assert.deepEqual(twice.waits, [1000, 3000]);
+ assert.deepEqual(twice.retries, [1, 2]);
+ assert.equal(twice.sent, 3);
+});
+
+test('P3: after two automatic retries it stops and shows the manual Retry', async () => {
+ const r = await runUpload(['drop', 'drop', 'drop', 201]);
+ assert.equal(r.sent, 3, 'one try plus two retries');
+ assert.deepEqual(r.waits, [1000, 3000]);
+ assert.equal(r.err?.status, 0);
+ assert.equal(a.uploadRetryable(r.err.status), true, 'manual Retry still offered');
+});
+
+test('P3: 413, 415 and 400 never retry; neither do 500 or 401', async () => {
+ for (const st of [413, 415, 400, 500, 401]) {
+ const r = await runUpload([st, 201]);
+ assert.equal(r.err?.status, st, `HTTP ${st} fails`);
+ if (st === 413) assert.equal(r.err.code, 'too_large');
+ assert.equal(r.sent, 1, `HTTP ${st}: no second request`);
+ assert.deepEqual(r.waits, []);
+ }
+ for (const st of [0, 502, 503, 504]) assert.equal(a.uploadAutoRetryable(st), true);
+ for (const st of [400, 401, 413, 415, 429, 500]) assert.equal(a.uploadAutoRetryable(st), false);
+ assert.equal(a.uploadAutoRetryable(400, 'interrupted'), true);
+ assert.equal(a.uploadRetryable(400, 'interrupted'), true);
+ assert.equal(a.uploadRetryable(400, 'empty'), false);
+ // api.md's 413 text is shown as the server wrote it
+ assert.equal(a.uploadErrorText(413, 'Videos can be at most 100 MB.'), 'Videos can be at most 100 MB.');
+});
+
+test('P3: cancelling while it waits to retry stops it', async () => {
+ const fake = installFakeXhr(['drop', 201]);
+ try {
+ const ctrl = new AbortController();
+ const file = Object.assign(new Blob([new Uint8Array(8)]), { name: 'clip.mp4' });
+ const p = a.uploadWithRetry(file, () => {}, ctrl.signal, { delays: [50, 50], onRetrying: () => ctrl.abort() });
+ await assert.rejects(p, (e) => e.name === 'AbortError');
+ assert.equal(fake.sent.length, 1);
+ } finally {
+ fake.restore();
+ }
+});