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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(workbench): polish chat media — capped image previews, lightbox, voice controls (#400)
Call White7d1596646714
diff --git a/ui/src/components/ui/chat-image.tsx b/ui/src/components/ui/chat-image.tsxnew file mode 100644index 000000000..5e6493137--- /dev/null+++ b/ui/src/components/ui/chat-image.tsx@@ -0,0 +1,74 @@+import * as React from 'react';+import { useTranslation } from 'react-i18next';+import { Download } from 'lucide-react';++import { Button } from '@/components/ui/button';+import { useImageViewer } from '@/components/ui/image-viewer';+import { cn } from '@/lib/utils';++// When a markdown image is wrapped in a link (``[](href)``),+// react-markdown nests the image inside the outer <a>. The Markdown ``a`` handler+// wraps such children in this provider so the ChatImage inside renders WITHOUT+// its own download <a> (nested anchors are invalid HTML) and without the+// lightbox click (the surrounding link is the intended action) — just the+// capped <img>.+const LinkedImageContext = React.createContext(false);+export const LinkedImageProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => (+ <LinkedImageContext.Provider value={true}>{children}</LinkedImageContext.Provider>+);++// The width cap is an inline style so it beats the ``.vr-markdown img {+// max-width: 100% }`` descendant rule.+const IMG_BOX: React.CSSProperties = { maxWidth: 'min(22rem, 100%)', maxHeight: '15rem' };+const IMG_CLASS = 'block h-auto w-auto rounded-lg border border-border object-contain';++// One inline chat image — used by both the Markdown renderer (agent replies) and+// the user-attachment renderer (ChatPage). Capped to a preview width and shown+// at its natural aspect (never stretched / full-width); click to open the+// lightbox; hover reveals a download button.+export const ChatImage: React.FC<{ src: string; alt?: string; className?: string }> = ({ src, alt, className }) => {+ const { t } = useTranslation();+ const viewer = useImageViewer();+ const linked = React.useContext(LinkedImageContext);++ // Inside a markdown link: a bare capped image — no nested download anchor and+ // no lightbox click stealing the link.+ if (linked) {+ return (+ <img src={src} alt={alt || ''} loading="lazy" style={IMG_BOX} className={cn('my-1 align-bottom', IMG_CLASS, className)} />+ );+ }++ return (+ <span className={cn('group relative my-1 inline-block max-w-full align-bottom', className)}>+ <img+ src={src}+ alt={alt || ''}+ loading="lazy"+ onClick={() => viewer?.open(src)}+ style={IMG_BOX}+ className={cn(IMG_CLASS, viewer ? 'cursor-zoom-in' : '')}+ />+ <Button+ asChild+ variant="ghost"+ size="icon"+ // Overlay badge on the image corner: smaller than a standard icon button,+ // dark translucent, revealed on hover. Inline color/decoration override+ // because this <a> can render inside ``.vr-markdown`` whose ``a`` rule+ // would otherwise tint it cyan + underline.+ className="absolute right-2 top-2 size-7 rounded-md bg-black/55 text-white opacity-0 backdrop-blur-sm transition hover:bg-black/70 hover:text-white group-hover:opacity-100"+ >+ <a+ href={`${src}?download=1`}+ download+ onClick={(e) => e.stopPropagation()}+ aria-label={t('chat.media.download')}+ style={{ color: '#fff', textDecoration: 'none' }}+ >+ <Download className="size-4" />+ </a>+ </Button>+ </span>+ );+};diff --git a/ui/src/components/ui/image-viewer.tsx b/ui/src/components/ui/image-viewer.tsxnew file mode 100644index 000000000..662d93732--- /dev/null+++ b/ui/src/components/ui/image-viewer.tsx@@ -0,0 +1,159 @@+import * as React from 'react';+import { useTranslation } from 'react-i18next';+import { ChevronLeft, ChevronRight, Download, X } from 'lucide-react';++import { Button } from '@/components/ui/button';++// A session-scoped image lightbox. ChatPage computes the ordered list of media-+// proxy image URLs in the transcript and wraps the page in a provider; any chat+// image (markdown inline image or a user attachment) opens it via ``open(src)``,+// and the lightbox pages left/right through the whole session's images. Used+// through the optional context so the shared Markdown renderer keeps working+// (no-op) where there's no provider (e.g. the agent-config editor preview).++type ImageViewerContextValue = { open: (src: string) => void };++const ImageViewerContext = React.createContext<ImageViewerContextValue | null>(null);++export function useImageViewer(): ImageViewerContextValue | null {+ return React.useContext(ImageViewerContext);+}++// Overlay controls sit on a dark backdrop, so the shared Button's themed+// foreground/hover (tuned for app surfaces) would be invisible here — override+// to white-on-translucent while still inheriting Button's sizing/focus/disabled+// behavior instead of hand-rolling a <button>.+const OVERLAY_BTN = 'bg-white/10 text-white hover:bg-white/20 hover:text-white';++export const ImageViewerProvider: React.FC<{ images: string[]; children: React.ReactNode }> = ({+ images,+ children,+}) => {+ const { t } = useTranslation();+ // Track the *displayed URL*, not an index. ``images`` is recomputed on every+ // streamed message, so a stored index would drift; and keeping the context+ // value (``open``) free of any ``images`` dependency means it stays stable, so+ // chat images don't re-render on every streaming tick. A clicked src that+ // isn't in the list (shouldn't happen for our own clean proxy URLs, but be+ // safe) still shows exactly what was clicked — paging just turns off for it.+ const [src, setSrc] = React.useState<string | null>(null);++ const open = React.useCallback((next: string) => setSrc(next), []);+ const close = React.useCallback(() => setSrc(null), []);++ const index = src ? images.indexOf(src) : -1;+ const pageable = index >= 0 && images.length > 1;+ const step = React.useCallback(+ (delta: number) => {+ if (index < 0 || images.length === 0) return;+ setSrc(images[(index + delta + images.length) % images.length]);+ },+ [index, images],+ );++ React.useEffect(() => {+ if (src === null) return;+ // The lightbox is a modal: while open it OWNS Escape / arrows. Listen in the+ // capture phase and stop immediate propagation on the keys we handle so a+ // lower global handler (notably the Composer's "Escape aborts recording")+ // can't also fire — Escape here must only close the viewer, not discard an+ // in-progress voice recording. Capture runs before any bubble-phase window+ // listener regardless of registration order, so ownership is deterministic.+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.stopImmediatePropagation();+ close();+ } else if (e.key === 'ArrowLeft') {+ e.stopImmediatePropagation();+ step(-1);+ } else if (e.key === 'ArrowRight') {+ e.stopImmediatePropagation();+ step(1);+ }+ };+ window.addEventListener('keydown', onKey, { capture: true });+ return () => window.removeEventListener('keydown', onKey, { capture: true });+ }, [src, close, step]);++ const ctx = React.useMemo(() => ({ open }), [open]);++ return (+ <ImageViewerContext.Provider value={ctx}>+ {children}+ {src && (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 p-6 backdrop-blur-sm"+ onClick={close}+ role="dialog"+ aria-modal="true"+ >+ <div className="absolute right-4 top-4 flex items-center gap-2">+ <Button+ asChild+ variant="ghost"+ size="icon"+ className={OVERLAY_BTN}+ >+ <a+ href={`${src}?download=1`}+ download+ onClick={(e) => e.stopPropagation()}+ aria-label={t('chat.media.download')}+ >+ <Download className="size-4" />+ </a>+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onClick={close}+ aria-label={t('chat.viewer.close')}+ className={OVERLAY_BTN}+ >+ <X className="size-4" />+ </Button>+ </div>+ {pageable && (+ <>+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ step(-1);+ }}+ aria-label={t('chat.viewer.previous')}+ className={`absolute left-4 top-1/2 -translate-y-1/2 rounded-full ${OVERLAY_BTN}`}+ >+ <ChevronLeft className="size-5" />+ </Button>+ <Button+ variant="ghost"+ size="icon"+ onClick={(e) => {+ e.stopPropagation();+ step(1);+ }}+ aria-label={t('chat.viewer.next')}+ className={`absolute right-4 top-1/2 -translate-y-1/2 rounded-full ${OVERLAY_BTN}`}+ >+ <ChevronRight className="size-5" />+ </Button>+ </>+ )}+ <img+ src={src}+ alt=""+ onClick={(e) => e.stopPropagation()}+ className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain shadow-2xl"+ />+ {pageable && (+ <span className="absolute bottom-4 left-1/2 -translate-x-1/2 rounded-full bg-white/10 px-3 py-1 font-mono text-[11px] text-white">+ {index + 1} / {images.length}+ </span>+ )}+ </div>+ )}+ </ImageViewerContext.Provider>+ );+};diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsxindex 6d48ad751..9244e4575 100644--- a/ui/src/components/ui/markdown.tsx+++ b/ui/src/components/ui/markdown.tsx@@ -2,6 +2,7 @@ import * as React from 'react';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';+import { ChatImage, LinkedImageProvider } from '@/components/ui/chat-image';import { FileCard } from '@/components/ui/file-card';import { isProxyMediaUrl } from '@/lib/mediaProxy';import { cn } from '@/lib/utils';@@ -37,7 +38,7 @@ export const Markdown: React.FC<{ content: string; className?: string; interactiif (!src) return null;const url = String(src);if (interactive && isProxyMediaUrl(url)) {- return <img src={url} alt={alt || ''} loading="lazy" />;+ return <ChatImage src={url} alt={alt || ''} />;}const label = `🖼 ${alt || url}`;return interactive ? (@@ -58,9 +59,11 @@ export const Markdown: React.FC<{ content: string; className?: string; interactireturn <FileCard href={url}>{children}</FileCard>;}if (!interactive) return <span>{children}</span>;+ // Wrap children so a nested ChatImage (``[](href)``) renders+ // bare — without its own download anchor inside this one.return (<a href={url} target="_blank" rel="noopener noreferrer nofollow">- {children}+ <LinkedImageProvider>{children}</LinkedImageProvider></a>);},diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex acd93fd5f..68771d849 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -13,7 +13,9 @@ import { formatLocalDateTime } from '../../lib/relativeTime';import { fetchBackendModels } from '../../lib/backendModels';import { resolveEffortOptions } from '../../lib/effortOptions';import { Button } from '../ui/button';+import { ChatImage } from '../ui/chat-image';import { FileCard } from '../ui/file-card';+import { ImageViewerProvider } from '../ui/image-viewer';import { Input } from '../ui/input';import { Markdown } from '../ui/markdown';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';@@ -624,6 +626,34 @@ export const ChatPage: React.FC = () => {[api, session],);+ // Ordered media-proxy image URLs across the whole session — feeds the lightbox+ // so it pages left/right through every image, in render order (each message's+ // attachments first, then any inline images in its text).+ const sessionImages = useMemo(() => {+ const urls: string[] = [];+ const seen = new Set<string>();+ const push = (u: string) => {+ if (u && isProxyMediaUrl(u) && !seen.has(u)) {+ seen.add(u);+ urls.push(u);+ }+ };+ for (const m of messages) {+ const atts = (m.content as { attachments?: Array<Record<string, unknown>> })?.attachments;+ if (Array.isArray(atts)) {+ for (const a of atts) {+ if (a?.kind === 'image' || String(a?.mime || '').startsWith('image/')) push(String(a?.url || ''));+ }+ }+ if (m.text) {+ const re = /!\[[^\]]*\]\((\/api\/sessions\/[^)\s]+\/media\/[^)\s]+)\)/g;+ let match: RegExpExecArray | null;+ while ((match = re.exec(m.text)) !== null) push(match[1]);+ }+ }+ return urls;+ }, [messages]);+if (!sessionId) {return <ChatMissing onBack={() => navigate('/inbox')} />;}@@ -669,8 +699,9 @@ export const ChatPage: React.FC = () => {// ``calc(100dvh-4rem)`` double-subtracted the (already-cancelled) padding// and left a 4rem dead gap below the compose bar. On mobile the sticky// ``h-16`` header occupies 4rem at the top, so subtract that instead.- <div className="-mx-4 -my-5 flex h-[calc(100dvh-4rem)] flex-col md:-mx-10 md:-my-8 md:h-[100dvh]">- <ChatHeaderBar session={session} agents={agents} onPatch={patch} onBack={() => navigate('/inbox')} />+ <ImageViewerProvider images={sessionImages}>+ <div className="-mx-4 -my-5 flex h-[calc(100dvh-4rem)] flex-col md:-mx-10 md:-my-8 md:h-[100dvh]">+ <ChatHeaderBar session={session} agents={agents} onPatch={patch} onBack={() => navigate('/inbox')} />{error && (<div className="mx-auto mt-3 w-full max-w-[1080px] rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">@@ -691,7 +722,8 @@ export const ChatPage: React.FC = () => {initialDraft={initialDraft}onDraftChange={onDraftChange}/>- </div>+ </div>+ </ImageViewerProvider>);};@@ -827,7 +859,7 @@ const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit }) => {<buttontype="button"onClick={() => setEditing(true)}- className="group inline-flex flex-1 items-center gap-2 truncate text-left text-[16px] font-bold text-foreground hover:text-foreground"+ className="group inline-flex min-w-0 items-center gap-2 truncate text-left text-[16px] font-bold text-foreground hover:text-foreground"><span className="truncate">{title || t('chat.untitled')}</span><Pencil className="size-3.5 shrink-0 text-muted opacity-0 transition-opacity group-hover:opacity-100" />@@ -969,7 +1001,7 @@ const AgentRoutePicker: React.FC<AgentRoutePickerProps> = ({ session, agents, on<Buttontype="button"variant="outline"- className="ml-auto inline-flex h-auto max-w-[62%] items-center justify-start gap-1.5 rounded-lg border-cyan/40 bg-surface-2 px-2.5 py-1.5 text-[12px] font-normal hover:bg-cyan/[0.06]"+ className="inline-flex h-auto max-w-[62%] items-center justify-start gap-1.5 rounded-lg border-cyan/40 bg-surface-2 px-2.5 py-1.5 text-[12px] font-normal hover:bg-cyan/[0.06]">{backend && (<span className="inline-flex shrink-0 items-center gap-1 rounded border border-cyan/30 bg-cyan/[0.08] px-1.5 py-0.5 font-mono text-[9px] font-bold uppercase text-cyan">@@ -1310,13 +1342,7 @@ const MessageRow: React.FC<{ message: WorkbenchMessage; session: WorkbenchSessioconst isImage =(att?.kind === 'image' || String(att?.mime || '').startsWith('image/')) && isProxyMediaUrl(url);return isImage ? (- <img- key={i}- src={url}- alt={typeof att?.name === 'string' ? att.name : ''}- loading="lazy"- className="max-h-60 max-w-full rounded-lg border border-border"- />+ <ChatImage key={i} src={url} alt={typeof att?.name === 'string' ? att.name : ''} />) : (<FileCard key={i} href={url}>{typeof att?.name === 'string' ? att.name : 'file'}diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 5dd9045b7..09229840b 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -95,6 +95,8 @@ export const Composer: React.FC<ComposerProps> = ({const chunksRef = useRef<Blob[]>([]);const streamRef = useRef<MediaStream | null>(null);const unmountedRef = useRef(false);+ // Set just before stopping to mean "discard, don't transcribe" (ESC / unmount).+ const abortedRef = useRef(false);// Upload + voice are scoped to a session (the upload endpoint needs one); the// home composer leaves them off.@@ -209,8 +211,12 @@ export const Composer: React.FC<ComposerProps> = ({recorder.onstop = async () => {stream.getTracks().forEach((track) => track.stop());streamRef.current = null;+ const aborted = abortedRef.current;+ abortedRef.current = false;if (unmountedRef.current) return;setRecording(false);+ // ESC (or unmount) aborted the recording → mic released above, discard it.+ if (aborted) return;const blob = new Blob(chunksRef.current, { type: recorder.mimeType || 'audio/webm' });if (!blob.size) return;setTranscribing(true);@@ -232,6 +238,7 @@ export const Composer: React.FC<ComposerProps> = ({if (!unmountedRef.current) setTranscribing(false);}};+ abortedRef.current = false;recorderRef.current = recorder;recorder.start();setRecording(true);@@ -244,17 +251,37 @@ export const Composer: React.FC<ComposerProps> = ({}};+ const stopRecording = () => recorderRef.current?.stop(); // stop → transcribe+ const abortRecording = () => {+ abortedRef.current = true;+ recorderRef.current?.stop(); // stop → discard (onstop honors the abort flag)+ };const toggleRecording = () => {- if (recording) recorderRef.current?.stop();+ if (recording) stopRecording();else void startRecording();};+ // ESC aborts an in-progress recording (discard, no transcribe).+ useEffect(() => {+ if (!recording) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') {+ e.preventDefault();+ abortRecording();+ }+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [recording]);+const trimmed = value.trim();const readyAttachments = attachments.filter((a) => a.status === 'ready');const uploading = attachments.some((a) => a.status === 'uploading');// Send on text OR a ready attachment (attachment-only runs a turn so the agent- // reads the files); blocked while an upload is still in flight.- const canSubmit = (trimmed.length > 0 || readyAttachments.length > 0) && !uploading && !disabled;+ // reads the files); blocked while an upload is still in flight, and while+ // recording so neither the Send button nor the Enter key can fire mid-record.+ const canSubmit =+ (trimmed.length > 0 || readyAttachments.length > 0) && !uploading && !disabled && !recording;const update = (next: string) => {setValue(next);@@ -328,7 +355,7 @@ export const Composer: React.FC<ComposerProps> = ({)}>{mediaEnabled && (- <>+ <div className="flex items-end gap-0.5"><inputref={fileInputRef}type="file"@@ -362,7 +389,7 @@ export const Composer: React.FC<ComposerProps> = ({{transcribing ? <Loader2 className="size-4 animate-spin" /> : <Mic className="size-4" />}</Button>)}- </>+ </div>)}<textarearef={textareaRef}@@ -381,6 +408,21 @@ export const Composer: React.FC<ComposerProps> = ({placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"/>+ {/* While recording, a stop-voice button sits just left of Send (which is+ greyed out): click it to finish + transcribe; ESC aborts/discards. */}+ {recording && (+ <Button+ type="button"+ variant="destructive-soft"+ size="icon"+ onClick={stopRecording}+ disabled={transcribing}+ aria-label={t('chat.compose.stopRecording')}+ className="size-9 shrink-0 animate-pulse"+ >+ <Square className="size-4" />+ </Button>+ )}{/* 36px (size-9) icon button: pink-soft Stop while a turn runs, else aflat mint Send — design-system variants, not a glowy brand CTA. */}{busy ? (diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex afaa09c07..fc4f8a1c1 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1614,6 +1614,11 @@"preview": "Preview","download": "Download"},+ "viewer": {+ "close": "Close",+ "previous": "Previous",+ "next": "Next"+ },"queue": {"title": "Queued · {{count}}","sendNow": "Send now",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 38b457e72..d2e98ba47 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1613,6 +1613,11 @@"preview": "预览","download": "下载"},+ "viewer": {+ "close": "关闭",+ "previous": "上一张",+ "next": "下一张"+ },"queue": {"title": "排队中 · {{count}}","sendNow": "立即发送",