Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(workbench): multi-file + drag-and-drop upload in chat (#512)

Call Whiteb235d3ab2273
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 97bcd1787..bfab71efd 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,7 +1,7 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
-import { ArrowLeft, Bell, Bot, ChevronDown, Clock, Info, Loader2, MessageSquare, Pencil, X } from 'lucide-react';
+import { ArrowLeft, Bell, Bot, ChevronDown, Clock, Info, Loader2, MessageSquare, Pencil, UploadCloud, X } from 'lucide-react';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
@@ -12,6 +12,7 @@ import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
import { isProxyMediaUrl } from '../../lib/mediaProxy';
import { formatLocalDateTime } from '../../lib/relativeTime';
+import { useFileDrop } from '../../lib/useFileDrop';
import { AgentRoutePicker } from './AgentRoutePicker';
import { InstallHint } from '../InstallHint';
import { Button } from '../ui/button';
@@ -21,7 +22,7 @@ import { ImageViewerProvider } from '../ui/image-viewer';
import { FileViewerProvider } from '../ui/file-viewer';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
-import { Composer, type ComposerAttachment } from './Composer';
+import { Composer, type ComposerAttachment, type ComposerHandle } from './Composer';
import { QuickReplies } from './QuickReplies';
// While a turn is in flight, reconcile the working/Stop state against the
@@ -95,6 +96,16 @@ export const ChatPage: React.FC = () => {
const chatSurfaceRef = useRef<HTMLDivElement>(null);
useIosKeyboardInset(chatSurfaceRef);
+ // Chat-page-wide drag-and-drop: dropping files anywhere over the chat surface
+ // (not just the input row) stages them on the composer via its imperative
+ // handle. Desktop-only in practice — touch fires no drag events — and disabled
+ // until a session exists (the upload endpoint is session-scoped).
+ const composerRef = useRef<ComposerHandle>(null);
+ const { dragging: fileDragging, handlers: fileDropHandlers } = useFileDrop(
+ (files) => composerRef.current?.addFiles(files),
+ { disabled: !sessionId },
+ );
+
// Back returns to the page the user came from, not a hardcoded inbox.
// location.key === 'default' means /chat was the first history entry (deep
// link / refresh) with nothing to pop back to — fall back to the inbox then.
@@ -824,8 +835,20 @@ export const ChatPage: React.FC = () => {
there). */}
<div
ref={chatSurfaceRef}
- className="fixed inset-0 z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:static md:inset-auto md:z-auto md:-mx-10 md:-my-8 md:h-[var(--app-vvh)] md:bg-transparent md:pt-0"
+ className="fixed inset-0 z-40 flex flex-col bg-background pt-[env(safe-area-inset-top)] md:relative md:inset-auto md:z-auto md:-mx-10 md:-my-8 md:h-[var(--app-vvh)] md:bg-transparent md:pt-0"
+ {...fileDropHandlers}
>
+ {/* Drag-and-drop overlay: shown while files hover anywhere over the chat
+ surface. ``pointer-events-none`` lets the drag events bubble to this
+ container, whose drop handler stages them on the composer. */}
+ {fileDragging && (
+ <div className="pointer-events-none absolute inset-0 z-10 m-2 flex items-center justify-center rounded-2xl border-2 border-dashed border-mint/60 bg-background/85 backdrop-blur-sm md:m-3">
+ <div className="flex flex-col items-center gap-2 text-mint">
+ <UploadCloud className="size-7" />
+ <span className="text-[13px] font-medium">{t('chat.compose.dropOverlay')}</span>
+ </div>
+ </div>
+ )}
<ChatHeaderBar
session={session}
agents={agents}
@@ -855,6 +878,7 @@ export const ChatPage: React.FC = () => {
+ local value reset, instead of carrying across sessions (Codex P2). */}
<Compose
key={sessionId}
+ composerRef={composerRef}
onSend={sendMessage}
onStop={stopMessage}
busy={working}
@@ -913,6 +937,7 @@ const QueueStrip: React.FC<{
};
interface ComposeProps {
+ composerRef: React.Ref<ComposerHandle>;
onSend: (text: string, attachments?: ComposerAttachment[]) => void;
onStop: () => void;
busy: boolean;
@@ -921,7 +946,7 @@ interface ComposeProps {
onDraftChange: (text: string) => void;
}
-const Compose: React.FC<ComposeProps> = ({ onSend, onStop, busy, sessionId, initialDraft, onDraftChange }) => (
+const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange }) => (
// shrink-0 pins the bar at the bottom of the fixed-height chat container; the
// gradient fades the transcript out behind it (no opaque band / hard border)
// so the input sits close to the bottom edge. The input row is the shared
@@ -931,6 +956,7 @@ const Compose: React.FC<ComposeProps> = ({ onSend, onStop, busy, sessionId, init
style={{ background: 'linear-gradient(to top, var(--background) 65%, transparent)' }}
>
<Composer
+ ref={composerRef}
onSend={onSend}
onStop={onStop}
busy={busy}
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 47e90dca7..ef9435bc8 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from 'react';
+import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Clock, Loader2, Mic, Paperclip, Plus, Send, Square, Trash2, X } from 'lucide-react';
import clsx from 'clsx';
@@ -41,6 +41,16 @@ function readFileAsBase64(file: Blob): Promise<string> {
});
}
+// Parallel-upload pool size. A multi-file batch reads each file as base64
+// (~33% larger) and POSTs it; cap how many are in flight so a big drop of large
+// files (up to 25 MB each) doesn't materialize every request body at once.
+const UPLOAD_CONCURRENCY = 4;
+
+// Unique-enough id for an optimistic attachment chip before the server token
+// lands. Date.now() collides within a batch, so the random suffix separates
+// files staged in the same tick.
+const newLocalId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+
// Transcribe a recorded clip. Prefer a direct upload to avibe.bot (no tunnel
// relay — the audio doesn't detour through the user's machine); fall back to the
// local relay endpoint when the cloud token is unavailable (local access / not
@@ -99,12 +109,18 @@ export interface ComposerProps {
autoFocus?: boolean;
}
+export interface ComposerHandle {
+ /** Stage + upload files from outside the composer — e.g. a chat-page-wide
+ * drag-and-drop that drops onto the transcript rather than the input row. */
+ addFiles: (files: File[]) => void;
+}
+
// The chat-style input row: an auto-growing textarea + a Send/Stop icon button,
// plus (when ``sessionId`` is set) attachment upload and voice input on the left.
// Shared by the chat view (ChatPage) and the Workbench home so both use one input
// component instead of each hand-rolling its own. Owns its draft value; callers
// react via onSend / onDraftChange. design.pen kxEkn.
-export const Composer: React.FC<ComposerProps> = ({
+export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer({
onSend,
busy = false,
onStop,
@@ -115,7 +131,7 @@ export const Composer: React.FC<ComposerProps> = ({
className,
sessionId,
autoFocus = false,
-}) => {
+}, ref) {
const { t } = useTranslation();
const [value, setValue] = useState('');
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
@@ -220,47 +236,81 @@ export const Composer: React.FC<ComposerProps> = ({
setAttachments((cur) => cur.filter((a) => a.localId !== localId));
};
+ // Upload one already-staged file (its chip exists as 'uploading'): POST it as
+ // base64-JSON, then flip the chip to ready (carrying the server token + proxy
+ // URL) or to error. ``sid`` is threaded in so the fan-out below stays typed
+ // after the session guard.
+ const uploadOne = async (file: File, localId: string, sid: string) => {
+ try {
+ const data = await readFileAsBase64(file);
+ const res = await apiFetch(`/api/sessions/${encodeURIComponent(sid)}/attachments`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: file.name, mime: file.type, data }),
+ });
+ const json = await res.json().catch(() => null);
+ if (!res.ok || !json?.token) throw new Error('upload failed');
+ setAttachments((cur) =>
+ cur.map((a) =>
+ a.localId === localId
+ ? {
+ ...a,
+ token: json.token,
+ url: json.url,
+ mime: json.mime || a.mime,
+ size: json.size ?? a.size,
+ kind: json.kind || a.kind,
+ width: typeof json.width === 'number' ? json.width : undefined,
+ height: typeof json.height === 'number' ? json.height : undefined,
+ status: 'ready',
+ }
+ : a,
+ ),
+ );
+ } catch {
+ setAttachments((cur) => cur.map((a) => (a.localId === localId ? { ...a, status: 'error' } : a)));
+ }
+ };
+
+ // Upload a whole batch — multi-select from the picker or a chat-page drag-drop
+ // (handed in via the imperative handle below). Stage every chip up front in one
+ // update so the user sees the full batch at once, then upload with bounded
+ // concurrency so a big drop of large files doesn't flood memory / the endpoint.
const uploadFiles = async (files: File[]) => {
if (!sessionId) return;
- for (const file of files) {
- const localId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
- const kind: 'image' | 'file' = file.type.startsWith('image/') ? 'image' : 'file';
- setAttachments((cur) => [
- ...cur,
- { localId, token: '', name: file.name, mime: file.type || 'application/octet-stream', size: file.size, kind, url: '', status: 'uploading' },
- ]);
- try {
- const data = await readFileAsBase64(file);
- const res = await apiFetch(`/api/sessions/${encodeURIComponent(sessionId)}/attachments`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: file.name, mime: file.type, data }),
- });
- const json = await res.json().catch(() => null);
- if (!res.ok || !json?.token) throw new Error('upload failed');
- setAttachments((cur) =>
- cur.map((a) =>
- a.localId === localId
- ? {
- ...a,
- token: json.token,
- url: json.url,
- mime: json.mime || a.mime,
- size: json.size ?? a.size,
- kind: json.kind || a.kind,
- width: typeof json.width === 'number' ? json.width : undefined,
- height: typeof json.height === 'number' ? json.height : undefined,
- status: 'ready',
- }
- : a,
- ),
- );
- } catch {
- setAttachments((cur) => cur.map((a) => (a.localId === localId ? { ...a, status: 'error' } : a)));
+ const sid = sessionId;
+ const staged = files.map((file) => ({ file, localId: newLocalId() }));
+ setAttachments((cur) => [
+ ...cur,
+ ...staged.map(({ file, localId }) => ({
+ localId,
+ token: '',
+ name: file.name,
+ mime: file.type || 'application/octet-stream',
+ size: file.size,
+ kind: file.type.startsWith('image/') ? ('image' as const) : ('file' as const),
+ url: '',
+ status: 'uploading' as const,
+ })),
+ ]);
+ const queue = [...staged];
+ const worker = async () => {
+ let item = queue.shift();
+ while (item) {
+ await uploadOne(item.file, item.localId, sid);
+ item = queue.shift();
}
- }
+ };
+ await Promise.all(Array.from({ length: Math.min(UPLOAD_CONCURRENCY, queue.length) }, worker));
};
+ // Expose file staging so a chat-page-wide drop zone (ChatPage) can hand off
+ // files dropped onto the transcript — the picker + chips still live here. No
+ // deps array → always runs the latest uploadFiles closure for this session.
+ useImperativeHandle(ref, () => ({
+ addFiles: (files: File[]) => void uploadFiles(files),
+ }));
+
const startRecording = async () => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
@@ -552,4 +602,4 @@ export const Composer: React.FC<ComposerProps> = ({
</div>
</div>
);
-};
+});
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 04c4dc2e2..5577d3578 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1781,7 +1781,8 @@
"voice": "Voice input",
"stopRecording": "Stop recording",
"cancelRecording": "Cancel recording",
- "removeAttachment": "Remove"
+ "removeAttachment": "Remove",
+ "dropOverlay": "Drop files to attach"
},
"media": {
"preview": "Preview",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b5886c528..1a1316d9d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1780,7 +1780,8 @@
"voice": "语音输入",
"stopRecording": "停止录音",
"cancelRecording": "取消录音",
- "removeAttachment": "移除"
+ "removeAttachment": "移除",
+ "dropOverlay": "拖放文件以添加"
},
"media": {
"preview": "预览",
diff --git a/ui/src/lib/useFileDrop.ts b/ui/src/lib/useFileDrop.ts
new file mode 100644
index 000000000..fd7c93529
--- /dev/null
+++ b/ui/src/lib/useFileDrop.ts
@@ -0,0 +1,106 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export interface FileDropHandlers {
+ onDragEnter: (e: React.DragEvent) => void;
+ onDragOver: (e: React.DragEvent) => void;
+ onDragLeave: (e: React.DragEvent) => void;
+ onDrop: (e: React.DragEvent) => void;
+}
+
+export interface UseFileDropResult {
+ /** True while a file drag is hovering the zone — drive a drop overlay off this. */
+ dragging: boolean;
+ /** Spread onto the drop-target element. */
+ handlers: FileDropHandlers;
+}
+
+// Whether a drag carries files (vs. selected text, a link, an in-page element).
+// File contents are only readable on ``drop`` for security, but the format list
+// in ``types`` is visible during enter/over/leave — enough to gate the overlay.
+function dragHasFiles(e: React.DragEvent): boolean {
+ return Array.from(e.dataTransfer?.types ?? []).includes('Files');
+}
+
+/**
+ * Drag-and-drop file capture for a single drop zone. Returns a ``dragging`` flag
+ * (true while a file drag hovers the zone) plus the handlers to spread onto the
+ * target element; ``onFiles`` fires once per drop with every dropped file.
+ *
+ * Tracks a depth counter rather than a bare boolean so dragging across the
+ * zone's children doesn't flicker the flag — each child fires its own
+ * enter/leave as the cursor crosses it, but the count only returns to zero when
+ * the drag truly leaves the zone. Only file drags arm the zone, and ``disabled``
+ * makes every handler a no-op (e.g. a text-only composer with no upload target).
+ */
+export function useFileDrop(
+ onFiles: (files: File[]) => void,
+ options?: { disabled?: boolean },
+): UseFileDropResult {
+ const disabled = options?.disabled ?? false;
+ const [dragging, setDragging] = useState(false);
+ const depth = useRef(0);
+
+ // Safety net for a drag that ends without a balancing dragleave on the zone —
+ // dropped outside it, or cancelled with ESC (OS file drags fire no dragend on
+ // an in-page source). Reset on any window-level drop/dragend so the overlay
+ // can't stick. While disabled the handlers are no-ops (dragging never arms),
+ // so there's nothing to listen for or reset.
+ useEffect(() => {
+ if (disabled) return;
+ const reset = () => {
+ depth.current = 0;
+ setDragging(false);
+ };
+ window.addEventListener('drop', reset);
+ window.addEventListener('dragend', reset);
+ return () => {
+ window.removeEventListener('drop', reset);
+ window.removeEventListener('dragend', reset);
+ };
+ }, [disabled]);
+
+ const onDragEnter = useCallback(
+ (e: React.DragEvent) => {
+ if (disabled || !dragHasFiles(e)) return;
+ e.preventDefault();
+ depth.current += 1;
+ setDragging(true);
+ },
+ [disabled],
+ );
+
+ const onDragOver = useCallback(
+ (e: React.DragEvent) => {
+ if (disabled || !dragHasFiles(e)) return;
+ // Required: without preventDefault the element rejects the drop and the
+ // browser opens the file instead.
+ e.preventDefault();
+ if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
+ },
+ [disabled],
+ );
+
+ const onDragLeave = useCallback(
+ (e: React.DragEvent) => {
+ if (disabled || !dragHasFiles(e)) return;
+ e.preventDefault();
+ depth.current = Math.max(0, depth.current - 1);
+ if (depth.current === 0) setDragging(false);
+ },
+ [disabled],
+ );
+
+ const onDrop = useCallback(
+ (e: React.DragEvent) => {
+ if (disabled) return;
+ e.preventDefault();
+ depth.current = 0;
+ setDragging(false);
+ const files = Array.from(e.dataTransfer?.files ?? []);
+ if (files.length) onFiles(files);
+ },
+ [disabled, onFiles],
+ );
+
+ return { dragging, handlers: { onDragEnter, onDragOver, onDragLeave, onDrop } };
+}