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.

frontend: attachments in chat, plus "Waiting for you" badge (batch2 D)

Pixel (kwant bot)0d1ca58608c1
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index e8ca1aad..d8d993d8 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -47,6 +47,7 @@ import {
import type { PinnedItem } from './components/Instructions';
import type { EditTab } from './components/NewAgentModal';
import { Skill, applySkillEvent, pendingByKwant, skillsApi } from './skills';
+import { AttachmentRef, sendAttachmentErrorText } from './attachments';
import {
Question,
QuestionMeta,
@@ -840,7 +841,7 @@ export const App: React.FC = () => {
});
};
- const handleSendMessage = async (text: string) => {
+ const handleSendMessage = async (text: string, attachments: AttachmentRef[] = []) => {
const targetId = openCtx;
const threadId = openThreadId;
const isTargetChannel = isChannel;
@@ -867,6 +868,7 @@ export const App: React.FC = () => {
sender_role: 'user',
sender_id: 'PlayerHero',
text,
+ meta: attachments.length ? JSON.stringify({ attachments }) : null,
};
const cached = messagesCacheRef.current[targetId] || messages;
const updated = [...cached, userMsg];
@@ -875,24 +877,26 @@ export const App: React.FC = () => {
setMessages(updated);
}
+ const attachment_ids = attachments.map((a) => a.id);
try {
const res = await fetch('/api/chat/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(
threadId
- ? { thread_id: threadId, prompt: text, sender_id: 'PlayerHero' }
+ ? { thread_id: threadId, prompt: text, sender_id: 'PlayerHero', attachment_ids }
: {
channel_id: isTargetChannel ? targetId : null,
kwant_id: !isTargetChannel ? targetId : null,
team_id: targetTeam || null,
prompt: text,
sender_id: 'PlayerHero',
+ attachment_ids,
},
),
});
if (!res.ok) {
- let message = `HTTP ${res.status}`;
+ let message = attachments.length ? sendAttachmentErrorText(res.status) ?? `HTTP ${res.status}` : `HTTP ${res.status}`;
try {
const data = await res.json();
if (typeof data?.error === 'string') message = data.error;
@@ -1709,7 +1713,8 @@ export const App: React.FC = () => {
error={threadErrors[currentKwant.id] ?? null}
openThreadId={openThreadId}
turns={turns}
- directBadge={threadBadge({ id: currentKwant.id, delegation: null }, turns)}
+ awaiting={awaitingTurns}
+ directBadge={threadBadge({ id: currentKwant.id, delegation: null }, turns, awaitingTurns)}
showArchived={showArchived}
onToggleArchived={() => setShowArchived((v) => !v)}
onOpenDirect={openDirectChat}
@@ -1723,6 +1728,7 @@ export const App: React.FC = () => {
badge={threadBadge(
{ id: shownThread.id, delegation: shownThread.delegation ? delegations[shownThread.delegation.id] ?? shownThread.delegation : null },
turns,
+ awaitingTurns,
)}
delegatedBy={kwantName(shownThread.delegation?.lead_kwant_id ?? shownThread.created_by)}
onBack={openDirectChat}
diff --git a/frontend/src/attachments.ts b/frontend/src/attachments.ts
new file mode 100644
index 00000000..06bdc86e
--- /dev/null
+++ b/frontend/src/attachments.ts
@@ -0,0 +1,176 @@
+// File attachments in chats: uploads from the composer and files agents share (batch 2 / D).
+import { parseMetaObject } from './questions';
+
+export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
+export const MAX_ATTACHMENTS = 10;
+
+/** What a message's `meta.attachments` holds. */
+export interface AttachmentRef {
+ id: string;
+ name: string;
+ mime: string;
+ size: number;
+}
+
+export interface Attachment extends AttachmentRef {
+ sha256: string;
+ source: 'user' | 'agent';
+ kwant_id: string | null;
+ context_id: string | null;
+ message_id: string | null;
+ created_at: string;
+ url: string;
+}
+
+const INLINE_IMAGES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+/** Only these render inline (the server serves everything else as a download). */
+export const isInlineImage = (mime: string) => INLINE_IMAGES.has(mime.toLowerCase());
+
+export const attachmentUrl = (id: string, download = false) =>
+ `/api/attachments/${encodeURIComponent(id)}/content${download ? '?download=1' : ''}`;
+
+export function formatBytes(n: number): string {
+ if (!Number.isFinite(n) || n < 0) return '';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(n < 10 * 1024 ? 1 : 0)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(n < 10 * 1024 * 1024 ? 1 : 0)} MB`;
+}
+
+/** A short type label for a file tile ("PDF", "PNG", "Text"). */
+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 === 'application/json') return 'JSON';
+ if (m === 'text/csv') return 'CSV';
+ if (m === 'text/markdown') return 'Markdown';
+ if (m.startsWith('text/')) return 'Text';
+ const ext = /\.([a-z0-9]{1,6})$/i.exec(name)?.[1];
+ return ext ? ext.toUpperCase() : 'File';
+}
+
+/** The files on a message (user uploads or an agent's `share_file`), skipping malformed entries. */
+export function parseAttachments(meta: unknown): AttachmentRef[] {
+ const m = parseMetaObject(meta);
+ if (!m || !Array.isArray(m.attachments)) return [];
+ return m.attachments.flatMap((a: unknown) => {
+ const x = a as Partial<AttachmentRef> | null;
+ if (!x || typeof x.id !== 'string' || !UUID_RE.test(x.id) || typeof x.name !== 'string') return [];
+ return [{ id: x.id, name: x.name, mime: typeof x.mime === 'string' ? x.mime : 'application/octet-stream', size: typeof x.size === 'number' ? x.size : 0 }];
+ });
+}
+
+/** 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.`;
+ return null;
+}
+
+/** Friendly text for an upload the server refused. */
+export function uploadErrorText(status: number, serverMessage?: string): string {
+ switch (status) {
+ case 413:
+ return 'Too big. Max 20 MB.';
+ case 415:
+ return "That file type isn't supported. Images, PDFs and text files work.";
+ case 400:
+ return serverMessage || 'The file is empty or its name is not allowed.';
+ case 401:
+ case 403:
+ return 'Your session ended. Sign in again.';
+ case 0:
+ return 'Upload interrupted. Check the connection and retry.';
+ default:
+ return serverMessage || `Upload failed (HTTP ${status}).`;
+ }
+}
+
+/** Why `/chat/send` refused a message's files, or null when the status isn't about them. */
+export function sendAttachmentErrorText(status: number): string | null {
+ if (status === 409) return 'A file here was already sent. Attach it again to resend.';
+ if (status === 400) return `Couldn't attach the files (unknown file, or more than ${MAX_ATTACHMENTS}).`;
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// Composer uploads
+
+export type UploadState = 'uploading' | 'done' | 'error';
+
+export interface PendingUpload {
+ key: string;
+ name: string;
+ size: number;
+ /** 0–1 */
+ progress: number;
+ state: UploadState;
+ error?: string;
+ attachment?: Attachment;
+}
+
+/** Room for more files: at most 10 per message. */
+export const uploadSlotsLeft = (items: PendingUpload[]) => Math.max(0, MAX_ATTACHMENTS - items.length);
+
+/** Sendable when there's text or a finished file, and nothing still uploading or failed. */
+export function composerReady(text: string, items: PendingUpload[]): boolean {
+ if (items.some((i) => i.state !== 'done')) return false;
+ return text.trim().length > 0 || items.length > 0;
+}
+
+export const readyAttachments = (items: PendingUpload[]): AttachmentRef[] =>
+ items.flatMap((i) => (i.state === 'done' && i.attachment ? [{ id: i.attachment.id, name: i.attachment.name, mime: i.attachment.mime, size: i.attachment.size }] : []));
+
+/**
+ * Uploads one file as the raw request body (`?name=`), reporting progress. XHR because fetch has
+ * no upload progress. Rejects with a friendly message; an abort rejects with `AbortError`.
+ */
+export function uploadAttachment(file: Blob & { name?: string }, onProgress: (fraction: number) => void, signal?: AbortSignal): Promise<Attachment> {
+ return new Promise((resolve, reject) => {
+ const xhr = new XMLHttpRequest();
+ xhr.open('POST', `/api/attachments?name=${encodeURIComponent(file.name || 'file')}`);
+ xhr.upload.onprogress = (e) => {
+ if (e.lengthComputable && e.total > 0) onProgress(Math.min(1, e.loaded / e.total));
+ };
+ xhr.onload = () => {
+ let body: unknown = null;
+ try {
+ body = JSON.parse(xhr.responseText);
+ } catch {
+ // not JSON
+ }
+ if (xhr.status === 201 || xhr.status === 200) {
+ 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 Error(uploadErrorText(xhr.status, msg)));
+ }
+ };
+ xhr.onerror = () => reject(new Error(uploadErrorText(0)));
+ xhr.onabort = () => reject(new DOMException('Upload cancelled', 'AbortError'));
+ signal?.addEventListener('abort', () => xhr.abort(), { once: true });
+ xhr.send(file);
+ });
+}
+
+/** Files from a paste or drop (ignores plain text and dragged links). */
+export function filesFrom(list: DataTransferItemList | FileList | null | undefined): File[] {
+ if (!list) return [];
+ const out: File[] = [];
+ for (let i = 0; i < list.length; i++) {
+ const item = list[i] as DataTransferItem | File;
+ if ('kind' in item) {
+ if (item.kind === 'file') {
+ const f = item.getAsFile();
+ if (f) out.push(f);
+ }
+ } else out.push(item);
+ }
+ return out;
+}
diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx
new file mode 100644
index 00000000..89586da4
--- /dev/null
+++ b/frontend/src/components/Attachments.tsx
@@ -0,0 +1,131 @@
+import React, { useState } from 'react';
+import { AlertCircle, Download, FileText, Loader2, RotateCw, X } from 'lucide-react';
+import { AttachmentRef, PendingUpload, attachmentUrl, fileKind, formatBytes, isInlineImage } from '../attachments';
+
+/**
+ * A file on a message: images as a thumbnail (opens full size), everything else as a tile.
+ * Both have a Download button; the server sends non-images as downloads only.
+ */
+export const FileTile: React.FC<{ file: AttachmentRef }> = ({ file }) => {
+ const [broken, setBroken] = useState(false);
+ const image = isInlineImage(file.mime) && !broken;
+ const download = (
+ <a
+ href={attachmentUrl(file.id, true)}
+ download={file.name}
+ aria-label={`Download ${file.name}`}
+ className="inline-flex items-center gap-1 shrink-0 px-2 py-1 rounded-lg text-[11px] font-medium text-sky-300 bg-sky-500/10 border border-sky-500/30 hover:bg-sky-500/20 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <Download size={12} aria-hidden="true" />
+ <span className="hidden sm:inline">Download</span>
+ </a>
+ );
+ const label = (
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-xs font-medium text-zinc-100" title={file.name}>
+ {file.name}
+ </span>
+ <span className="block text-[10px] text-zinc-500">
+ {fileKind(file.mime, file.name)} · {formatBytes(file.size)}
+ </span>
+ </span>
+ );
+
+ if (image) {
+ return (
+ <figure className="w-full sm:w-auto max-w-full sm:max-w-xs rounded-xl overflow-hidden border border-zinc-800 bg-zinc-900/80">
+ <a href={attachmentUrl(file.id)} target="_blank" rel="noopener noreferrer" className="block focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500">
+ <img
+ src={attachmentUrl(file.id)}
+ alt={file.name}
+ loading="lazy"
+ decoding="async"
+ onError={() => setBroken(true)}
+ className="block w-full sm:w-auto max-h-60 object-contain bg-zinc-950"
+ />
+ </a>
+ <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} />
+ </span>
+ {label}
+ {download}
+ </div>
+ );
+};
+
+export const FileTiles: React.FC<{ files: AttachmentRef[]; align?: 'start' | 'end' }> = ({ files, align = 'start' }) => (
+ <ul className={`mt-2 flex flex-wrap gap-2 w-full ${align === 'end' ? 'justify-end' : ''}`} aria-label={files.length === 1 ? 'Attached file' : `${files.length} attached files`}>
+ {files.map((f) => (
+ <li key={f.id} className="max-w-full">
+ <FileTile file={f} />
+ </li>
+ ))}
+ </ul>
+);
+
+/** A file in the composer: uploading (with progress), ready, or failed (with the reason and Retry). */
+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';
+ 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 ${
+ failed ? 'border-rose-500/40 bg-rose-500/10' : 'border-zinc-700/70 bg-zinc-800/70'
+ }`}
+ >
+ {item.state === 'uploading' ? (
+ <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" />
+ ) : (
+ <FileText size={12} className="shrink-0 text-zinc-400" aria-hidden="true" />
+ )}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate text-zinc-100" title={item.name}>
+ {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)}
+ </span>
+ </span>
+ {failed && onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ aria-label={`Retry ${item.name}`}
+ className="p-1 rounded text-zinc-300 hover:text-white hover:bg-zinc-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <RotateCw size={12} aria-hidden="true" />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={onRemove}
+ aria-label={item.state === 'uploading' ? `Cancel uploading ${item.name}` : `Remove ${item.name}`}
+ className="p-1 rounded text-zinc-400 hover:text-white hover:bg-zinc-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <X size={12} aria-hidden="true" />
+ </button>
+ {item.state === 'uploading' && (
+ <span
+ className="absolute left-0 bottom-0 h-0.5 bg-sky-400 transition-[width] duration-150"
+ style={{ width: `${pct}%` }}
+ role="progressbar"
+ aria-label={`Uploading ${item.name}`}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={pct}
+ />
+ )}
+ </li>
+ );
+};
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 129a288e..13b4eb97 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,5 +1,5 @@
import React, { useState, useRef, useEffect } from 'react';
-import { ArrowUp, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin } from 'lucide-react';
+import { ArrowUp, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, Cpu, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard, PendingApproval } from './ModernApprovalCard';
import { MentionPopover, MentionItem } from './MentionPopover';
@@ -11,6 +11,20 @@ import { groupDiscussionThreads, stripDiscussionMarkers } from '../discussionThr
import { PinnedInstructions, PinnedItem } from './Instructions';
import { DelegationMeta, parseDelegationMeta } from '../threads';
import { QuestionMeta, parseQuestionMeta } from '../questions';
+import {
+ AttachmentRef,
+ MAX_ATTACHMENTS,
+ PendingUpload,
+ composerReady,
+ filesFrom,
+ isSharedFileMessage,
+ parseAttachments,
+ preflightFile,
+ readyAttachments,
+ uploadAttachment,
+ uploadSlotsLeft,
+} from '../attachments';
+import { FileTiles, UploadChip } from './Attachments';
export interface ChatMessage {
id: string;
@@ -76,7 +90,8 @@ export interface ChatViewProps {
pendingApproval: PendingApproval | null;
isStreaming: boolean;
streamingSpeakerName?: string;
- onSendMessage: (text: string) => void;
+ /** `attachments` are files already uploaded from the composer. */
+ onSendMessage: (text: string, attachments: AttachmentRef[]) => void;
onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
@@ -264,6 +279,12 @@ export const ChatView: React.FC<ChatViewProps> = ({
const toggleVm = onToggleVmPane || (() => setInternalIsVmPaneOpen((prev) => !prev));
const [inputVal, setInputVal] = useState('');
+ const [uploads, setUploads] = useState<PendingUpload[]>([]);
+ const [uploadNote, setUploadNote] = useState<string | null>(null);
+ const [dragOver, setDragOver] = useState(false);
+ const uploadFiles = useRef(new Map<string, { file: File; abort: AbortController }>());
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const dragDepth = useRef(0);
const [openThoughts, setOpenThoughts] = useState<Record<string, boolean>>({});
const [copiedId, setCopiedId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
@@ -438,14 +459,96 @@ export const ChatView: React.FC<ChatViewProps> = ({
setTimeout(() => setCopiedId(null), 2000);
};
+ const patchUpload = (key: string, patch: Partial<PendingUpload>) =>
+ setUploads((list) => list.map((u) => (u.key === key ? { ...u, ...patch } : u)));
+
+ 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 }),
+ (err: Error) => {
+ if (err.name !== 'AbortError') patchUpload(key, { state: 'error', error: err.message });
+ },
+ );
+ };
+
+ /** Files from the picker, a drop or a paste: checked here, then uploaded right away. */
+ const addFiles = (files: File[]) => {
+ if (!files.length) return;
+ const room = uploadSlotsLeft(uploads);
+ const notes: string[] = [];
+ if (files.length > room) notes.push(`Up to ${MAX_ATTACHMENTS} files per message; ${files.length - room === 1 ? 'one was' : `${files.length - room} were`} left out.`);
+ const added: PendingUpload[] = [];
+ for (const file of files.slice(0, room)) {
+ const problem = preflightFile(file);
+ if (problem) {
+ notes.push(problem);
+ 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' });
+ startUpload(key, file);
+ }
+ setUploadNote(notes.length ? notes.join(' ') : null);
+ if (added.length) setUploads((list) => [...list, ...added]);
+ };
+
+ const removeUpload = (key: string) => {
+ uploadFiles.current.get(key)?.abort.abort();
+ uploadFiles.current.delete(key);
+ setUploads((list) => list.filter((u) => u.key !== key));
+ };
+
+ const retryUpload = (key: string) => {
+ const f = uploadFiles.current.get(key)?.file;
+ if (!f) return;
+ patchUpload(key, { state: 'uploading', progress: 0, error: undefined });
+ startUpload(key, f);
+ };
+
+ const hasFiles = (e: React.DragEvent) => Array.from(e.dataTransfer.types).includes('Files');
+ const dropHandlers = {
+ onDragEnter: (e: React.DragEvent) => {
+ if (!hasFiles(e)) return;
+ e.preventDefault();
+ dragDepth.current += 1;
+ setDragOver(true);
+ },
+ onDragOver: (e: React.DragEvent) => {
+ if (!hasFiles(e)) return;
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'copy';
+ },
+ onDragLeave: (e: React.DragEvent) => {
+ if (!hasFiles(e)) return;
+ dragDepth.current = Math.max(0, dragDepth.current - 1);
+ if (dragDepth.current === 0) setDragOver(false);
+ },
+ onDrop: (e: React.DragEvent) => {
+ if (!hasFiles(e)) return;
+ e.preventDefault();
+ dragDepth.current = 0;
+ setDragOver(false);
+ addFiles(filesFrom(e.dataTransfer.files));
+ textareaRef.current?.focus();
+ },
+ };
+
+ const canSend = composerReady(inputVal, uploads);
+ const stillUploading = uploads.some((u) => u.state === 'uploading');
+
const handleSubmit = (e?: React.FormEvent) => {
if (e) e.preventDefault();
// A reply in progress doesn't block the next message (it waits its turn); a team discussion does.
- if (!inputVal.trim() || (isStreaming && discussionState?.inProgress)) return;
+ if (!canSend || (isStreaming && discussionState?.inProgress)) return;
playSfx('click');
stickRef.current = true;
- onSendMessage(inputVal.trim());
+ onSendMessage(inputVal.trim(), readyAttachments(uploads));
setInputVal('');
+ setUploads([]);
+ setUploadNote(null);
+ uploadFiles.current.clear();
setMentionQuery(null);
setMentionStartIndex(-1);
if (textareaRef.current) {
@@ -499,6 +602,9 @@ export const ChatView: React.FC<ChatViewProps> = ({
const question = msg.meta && renderQuestion ? parseQuestionMeta(msg.meta) : null;
if (question && renderQuestion) return <React.Fragment key={msg.id}>{renderQuestion(msg, question, flashId === msg.id)}</React.Fragment>;
const isUser = msg.sender_role === 'user';
+ const files = msg.meta ? parseAttachments(msg.meta) : [];
+ // An agent's share_file note: the file tiles say it all.
+ const filesOnly = files.length > 0 && isSharedFileMessage(msg.meta);
const isThoughtOpen = !!openThoughts[msg.id];
const displayName = isUser ? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
@@ -549,6 +655,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
)}
{/* Message Body Bubble */}
+ {!filesOnly && (msg.text.trim() || !files.length) && (
<div
className={`p-4 sm:p-5 rounded-2xl text-sm leading-relaxed shadow-sm w-full ${
isUser
@@ -562,11 +669,13 @@ export const ChatView: React.FC<ChatViewProps> = ({
<MarkdownRenderer content={msg.text} />
)}
</div>
+ )}
+ {files.length > 0 && <FileTiles files={files} align={isUser ? 'end' : 'start'} />}
{!isUser && msg.tool_calls && <ToolCallsList raw={msg.tool_calls} />}
{/* Copy action */}
- {!isUser && (
+ {!isUser && !filesOnly && (
<div className="mt-1.5 flex items-center gap-2 text-zinc-500 text-xs">
<button
type="button"
@@ -948,8 +1057,36 @@ export const ChatView: React.FC<ChatViewProps> = ({
<form
onSubmit={handleSubmit}
- className="relative max-w-4xl mx-auto flex items-end gap-2 bg-zinc-900 border border-zinc-800 focus-within:border-zinc-700 rounded-2xl p-2 shadow-sm transition-all"
+ {...dropHandlers}
+ aria-label={`Message ${title}`}
+ className={`relative max-w-4xl mx-auto flex flex-wrap items-end gap-2 bg-zinc-900 border rounded-2xl p-2 shadow-sm transition-all ${
+ dragOver ? 'border-sky-500/70 bg-sky-950/30' : 'border-zinc-800 focus-within:border-zinc-700'
+ }`}
>
+ {dragOver && (
+ <div className="absolute inset-0 z-10 rounded-2xl border-2 border-dashed border-sky-400/70 bg-zinc-950/80 flex items-center justify-center gap-2 text-sm font-medium text-sky-200 pointer-events-none">
+ <Paperclip size={15} aria-hidden="true" /> Drop files to attach
+ </div>
+ )}
+ {(uploads.length > 0 || uploadNote) && (
+ <div className="basis-full min-w-0 px-1 pt-0.5 space-y-1.5">
+ {uploads.length > 0 && (
+ <ul className="flex flex-wrap gap-1.5 min-w-0" aria-label="Files to send">
+ {uploads.map((u) => (
+ <UploadChip key={u.key} item={u} onRemove={() => removeUpload(u.key)} onRetry={() => retryUpload(u.key)} />
+ ))}
+ </ul>
+ )}
+ {uploadNote && (
+ <p role="alert" className="flex items-start gap-2 text-[11px] text-amber-300">
+ <span className="min-w-0">{uploadNote}</span>
+ <button type="button" onClick={() => setUploadNote(null)} className="shrink-0 text-zinc-500 hover:text-zinc-300 underline-offset-2 hover:underline">
+ Dismiss
+ </button>
+ </p>
+ )}
+ </div>
+ )}
{isMentionOpen && (
<MentionPopover
items={matchingItems}
@@ -970,6 +1107,13 @@ export const ChatView: React.FC<ChatViewProps> = ({
checkMention(val, e.target.selectionStart);
}}
onKeyDown={handleKeyDown}
+ onPaste={(e) => {
+ const pasted = filesFrom(e.clipboardData.items);
+ if (pasted.length) {
+ e.preventDefault();
+ addFiles(pasted);
+ }
+ }}
onClick={(e) => {
checkMention(inputVal, (e.target as HTMLTextAreaElement).selectionStart);
}}
@@ -979,8 +1123,29 @@ export const ChatView: React.FC<ChatViewProps> = ({
}
}}
placeholder={`Message ${title}... (Enter to send, Shift+Enter for newline, @ to mention)`}
- className="flex-1 bg-transparent px-3 py-1.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"
+ className="flex-1 min-w-0 bg-transparent px-3 py-1.5 text-sm text-zinc-100 placeholder-zinc-500 focus:outline-none resize-none max-h-40 leading-relaxed font-sans"
+ />
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ hidden
+ tabIndex={-1}
+ onChange={(e) => {
+ addFiles(filesFrom(e.target.files));
+ e.target.value = '';
+ }}
/>
+ <button
+ 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.'}
+ aria-label="Attach files"
+ className="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0 text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 disabled:opacity-40 disabled:cursor-not-allowed transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
+ >
+ <Paperclip size={16} aria-hidden="true" />
+ </button>
{isStreaming && (
<button
@@ -993,13 +1158,14 @@ export const ChatView: React.FC<ChatViewProps> = ({
<Square size={12} fill="currentColor" aria-hidden="true" />
</button>
)}
- {!(isStreaming && (discussionState?.inProgress || !inputVal.trim())) && (
+ {!(isStreaming && (discussionState?.inProgress || !canSend)) && (
<button
type="submit"
- aria-label={isStreaming ? 'Send (waits for the current reply)' : 'Send'}
- disabled={!inputVal.trim()}
+ aria-label={stillUploading ? 'Send (waiting for uploads)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}
+ title={stillUploading ? 'Waiting for uploads to finish' : undefined}
+ disabled={!canSend}
className={`w-8 h-8 rounded-xl flex items-center justify-center transition-all flex-shrink-0 ${
- inputVal.trim()
+ canSend
? 'bg-sky-500 text-white hover:bg-sky-400 shadow-sm'
: 'bg-zinc-800 text-zinc-500 cursor-not-allowed'
}`}
diff --git a/frontend/src/components/ThreadBar.tsx b/frontend/src/components/ThreadBar.tsx
index 38e890cf..9e12ec05 100644
--- a/frontend/src/components/ThreadBar.tsx
+++ b/frontend/src/components/ThreadBar.tsx
@@ -1,9 +1,10 @@
import React, { useState } from 'react';
-import { Archive, ArchiveRestore, ArrowLeft, ArrowRightLeft, Loader2, MessageSquare, Plus, RotateCw, Square } from 'lucide-react';
+import { Archive, ArchiveRestore, ArrowLeft, ArrowRightLeft, HelpCircle, Loader2, MessageSquare, Plus, RotateCw, Square } from 'lucide-react';
import { Badge, BadgeKind, Thread, TurnMap, sortThreads, threadBadge } from '../threads';
const BADGE_STYLE: Record<BadgeKind, string> = {
working: 'text-sky-300 bg-sky-500/10 border-sky-500/30',
+ waiting: 'text-amber-300 bg-amber-500/10 border-amber-500/30',
queued: 'text-amber-300 bg-amber-500/10 border-amber-500/30',
done: 'text-emerald-300 bg-emerald-500/10 border-emerald-500/30',
failed: 'text-rose-300 bg-rose-500/10 border-rose-500/30',
@@ -16,6 +17,7 @@ export const StatusBadge: React.FC<{ badge: Badge; className?: string }> = ({ ba
className={`inline-flex items-center gap-1 px-1.5 py-px rounded-full border text-[10px] font-medium whitespace-nowrap ${BADGE_STYLE[badge.kind]} ${className}`}
>
{badge.kind === 'working' && <Loader2 size={9} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {badge.kind === 'waiting' && <HelpCircle size={9} aria-hidden="true" />}
{badge.label}
</span>
);
@@ -27,6 +29,8 @@ export interface ThreadBarProps {
error: string | null;
openThreadId: string | null;
turns: TurnMap;
+ /** Turns paused on a question to the person. */
+ awaiting?: ReadonlySet<string>;
/** Badge for the direct chat itself (working / queued). */
directBadge: Badge | null;
showArchived: boolean;
@@ -52,6 +56,7 @@ export const ThreadBar: React.FC<ThreadBarProps> = ({
error,
openThreadId,
turns,
+ awaiting,
directBadge,
showArchived,
onToggleArchived,
@@ -110,7 +115,7 @@ export const ThreadBar: React.FC<ThreadBarProps> = ({
)}
{visible.map((t) => {
- const badge = threadBadge(t, turns);
+ const badge = threadBadge(t, turns, awaiting);
const isOpen = openThreadId === t.id;
const delegated = t.kind === 'delegation';
return (
@@ -192,7 +197,7 @@ export interface ThreadHeaderProps {
export const ThreadHeader: React.FC<ThreadHeaderProps> = ({ thread, badge, delegatedBy, onBack, onStop, onArchive }) => {
const [busy, setBusy] = useState<'stop' | 'archive' | null>(null);
const [error, setError] = useState<string | null>(null);
- const running = badge?.kind === 'working' || badge?.kind === 'queued';
+ const running = badge?.kind === 'working' || badge?.kind === 'waiting' || badge?.kind === 'queued';
const act = async (kind: 'stop' | 'archive', fn: () => Promise<string | void>) => {
setBusy(kind);
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index b2bbfd5f..2e119d56 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -179,7 +179,7 @@ export const backgroundTurns = (turns: TurnMap, kwantId: string): TrackedTurn[]
// ---------------------------------------------------------------------------
// Thread list and status badges
-export type BadgeKind = 'working' | 'queued' | 'done' | 'failed' | 'interrupted' | 'cancelled';
+export type BadgeKind = 'working' | 'waiting' | 'queued' | 'done' | 'failed' | 'interrupted' | 'cancelled';
export interface Badge {
kind: BadgeKind;
@@ -194,10 +194,15 @@ const FINAL_LABEL: Record<string, Badge> = {
interrupted: { kind: 'interrupted', label: 'Interrupted' },
};
-/** A thread's badge: live turns win over the delegation record; idle user threads have none. */
-export function threadBadge(thread: Pick<Thread, 'id' | 'delegation'>, turns: TurnMap): Badge | null {
+/**
+ * A thread's badge: live turns win over the delegation record; idle user threads have none.
+ * A turn paused on the person's answer (`awaiting`) reads "Waiting for you", not "Working".
+ */
+export function threadBadge(thread: Pick<Thread, 'id' | 'delegation'>, turns: TurnMap, awaiting?: ReadonlySet<string>): Badge | null {
const live = turnsIn(turns, thread.id);
- if (live.some((t) => t.state === 'running')) return { kind: 'working', label: 'Working' };
+ const running = live.filter((t) => t.state === 'running');
+ if (running.some((t) => !awaiting?.has(t.turn_id))) return { kind: 'working', label: 'Working' };
+ if (running.length) return { kind: 'waiting', label: 'Waiting for you' };
const queued = live.find((t) => t.state === 'queued');
if (queued) {
const pos = queuePosition(turns, queued.turn_id);
diff --git a/frontend/tests/attachments.test.mjs b/frontend/tests/attachments.test.mjs
new file mode 100644
index 00000000..1194a146
--- /dev/null
+++ b/frontend/tests/attachments.test.mjs
@@ -0,0 +1,97 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const a = await loadBundled(`export * from './src/attachments';`);
+const ui = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { FileTiles, UploadChip } from './src/components/Attachments';
+ export const tiles = (files) => renderToStaticMarkup(React.createElement(FileTiles, { files }));
+ export const chip = (item) => renderToStaticMarkup(React.createElement('ul', null, React.createElement(UploadChip, { item, onRemove() {}, onRetry() {} })));
+`);
+
+const ID = '0b6f3c1e-2a4d-4e5f-8a9b-1c2d3e4f5a6b';
+const ID2 = '1b6f3c1e-2a4d-4e5f-8a9b-1c2d3e4f5a6b';
+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: 'e.txt', size: 0 }), /empty/);
+});
+
+test('server refusals read as plain language', () => {
+ assert.match(a.uploadErrorText(413), /Max 20 MB/);
+ assert.match(a.uploadErrorText(415), /isn't supported/);
+ assert.equal(a.uploadErrorText(400, 'bad name'), 'bad name');
+ assert.match(a.uploadErrorText(0), /interrupted/);
+ assert.match(a.uploadErrorText(500), /HTTP 500/);
+ assert.match(a.sendAttachmentErrorText(409), /already sent/);
+ assert.equal(a.sendAttachmentErrorText(500), null);
+});
+
+test('message files parse from meta and skip malformed or unsafe ids', () => {
+ const meta = JSON.stringify({ attachments: [
+ { id: ID, name: 'cat.png', mime: 'image/png', size: 2048 },
+ { id: '../../etc/passwd', name: 'x' },
+ { id: ID2, name: 'notes' },
+ null,
+ ] });
+ const files = a.parseAttachments(meta);
+ assert.deepEqual(files.map((f) => f.id), [ID, ID2]);
+ assert.equal(files[1].mime, 'application/octet-stream');
+ assert.deepEqual(a.parseAttachments('nope'), []);
+ assert.deepEqual(a.parseAttachments({ kind: 'ask_user' }), []);
+ assert.equal(a.isSharedFileMessage(JSON.stringify({ kind: 'file', attachments: [] })), true);
+ assert.equal(a.isSharedFileMessage(meta), false);
+});
+
+test('only raster images render inline; sizes and kinds are human', () => {
+ assert.equal(a.isInlineImage('image/PNG'), true);
+ assert.equal(a.isInlineImage('image/svg+xml'), false);
+ assert.equal(a.isInlineImage('application/pdf'), false);
+ assert.equal(a.formatBytes(512), '512 B');
+ assert.equal(a.formatBytes(1536), '1.5 KB');
+ assert.equal(a.formatBytes(3 * MB), '3.0 MB');
+ assert.equal(a.fileKind('image/jpeg', 'a.jpg'), 'JPG');
+ assert.equal(a.fileKind('application/octet-stream', 'data.zip'), 'ZIP');
+ assert.equal(a.attachmentUrl(ID, true), `/api/attachments/${ID}/content?download=1`);
+});
+
+test('the composer sends only when every file is uploaded', () => {
+ const done = { key: 'k1', name: 'a.png', size: 1, progress: 1, state: 'done', attachment: { id: ID, name: 'a.png', mime: 'image/png', size: 1 } };
+ const up = { key: 'k2', name: 'b.pdf', size: 1, progress: 0.4, state: 'uploading' };
+ const bad = { key: 'k3', name: 'c.exe', size: 1, progress: 0, state: 'error', error: 'nope' };
+ assert.equal(a.composerReady('', []), false);
+ assert.equal(a.composerReady('hi', []), true);
+ assert.equal(a.composerReady('', [done]), true);
+ assert.equal(a.composerReady('hi', [done, up]), false);
+ assert.equal(a.composerReady('hi', [bad]), false);
+ assert.deepEqual(a.readyAttachments([done, up]), [{ id: ID, name: 'a.png', mime: 'image/png', size: 1 }]);
+ assert.equal(a.uploadSlotsLeft(Array(9).fill(done)), 1);
+ assert.equal(a.uploadSlotsLeft(Array(12).fill(done)), 0);
+});
+
+test('tiles: images inline with a download, other files download only', () => {
+ const html = ui.tiles([
+ { id: ID, name: 'cat.png', mime: 'image/png', size: 2048 },
+ { id: ID2, name: 'report.pdf', mime: 'application/pdf', size: 3 * MB },
+ ]);
+ assert.match(html, new RegExp(`<img src="/api/attachments/${ID}/content" alt="cat.png" loading="lazy"`));
+ assert.doesNotMatch(html, new RegExp(`<img[^>]*${ID2}`));
+ assert.match(html, /aria-label="Download report.pdf"/);
+ assert.match(html, /PDF · 3.0 MB/);
+ assert.match(html, /aria-label="2 attached files"/);
+});
+
+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, /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/);
+ assert.match(failed, /Retry c.exe/);
+});
diff --git a/frontend/tests/questions.test.mjs b/frontend/tests/questions.test.mjs
index 06f8bb9e..6e4e27cf 100644
--- a/frontend/tests/questions.test.mjs
+++ b/frontend/tests/questions.test.mjs
@@ -98,3 +98,19 @@ test('answered and dismissed cards are closed', () => {
assert.match(dismissed, /Dismissed/);
assert.equal((dismissed.match(/disabled=""/g) || []).length, 2, 'every choice disabled');
});
+
+test('a turn paused on a question reads "Waiting for you", not "Working"', async () => {
+ const th = await loadBundled(`export * from './src/threads';`);
+ const turns = th.hydrateTurns([
+ { turn_id: 't1', kwant_id: 'cto', context_id: 'cto', thread_id: null, state: 'running', since: '2026-10-17T10:00:00Z' },
+ ]);
+ const direct = { id: 'cto', delegation: null };
+ assert.equal(th.threadBadge(direct, turns).label, 'Working');
+ assert.deepEqual(th.threadBadge(direct, turns, q.turnsAwaitingAnswer({ q1: rec({ turn_id: 't1' }) })), { kind: 'waiting', label: 'Waiting for you' });
+ // A second request it is working on in the same chat wins.
+ const both = th.hydrateTurns([
+ { turn_id: 't1', kwant_id: 'cto', context_id: 'cto', thread_id: null, state: 'running', since: '2026-10-17T10:00:00Z' },
+ { turn_id: 't2', kwant_id: 'cto', context_id: 'cto', thread_id: null, state: 'running', since: '2026-10-17T10:01:00Z' },
+ ]);
+ assert.equal(th.threadBadge(direct, both, new Set(['t1'])).kind, 'working');
+});