The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(conversations): handle empty conversation list gracefully
Steven Enamakel372b52e95086
diff --git a/app/src/features/conversations/Conversations.tsx b/app/src/features/conversations/Conversations.tsxindex 272a762047..1b1c80efbf 100644--- a/app/src/features/conversations/Conversations.tsx+++ b/app/src/features/conversations/Conversations.tsx@@ -114,8 +114,6 @@ import { useChatSurfaceRegistration } from './hooks/useChatSurfaceRegistration';import { ThreadList } from './threadList/ThreadList';const CHAT_MODEL_HINT = 'hint:chat';-type InputMode = 'text' | 'voice';-type ReplyMode = 'text' | 'voice';const debug = debugFactory('conversations');interface ConversationsProps {@@ -286,7 +284,6 @@ const Conversations = ({// Imperative handle onto the transcript's own background-processes panel// (its state now lives inside `ChatThreadView`) so the header badge below// can still open it without lifting that state back up.- const threadViewRef = useRef<ChatThreadViewHandle>(null);// Disclosure state for the three transcript-local overlays on the// assistant-ui surface. `ChatThreadView` owns an identical trio for the// legacy voice panel, but it is not mounted on `/chat` any more, so the@@ -318,12 +315,6 @@ const Conversations = ({enabled: () => selectedThreadId !== null && composer !== 'mic-cloud',keywords: ['agent', 'process', 'source', 'timeline', 'run'],});- const [inputMode, setInputMode] = useState<InputMode>('text');- const [replyMode, setReplyMode] = useState<ReplyMode>('text');- const [isRecording, setIsRecording] = useState(false);- const [isTranscribing, setIsTranscribing] = useState(false);- const [voiceStatus, setVoiceStatus] = useState<string | null>(null);- const [isPlayingReply, setIsPlayingReply] = useState(false);// Measured height of the floating composer footer (page variant only). The// footer is `absolute`ly positioned over the scroll area, so the message list// needs matching bottom padding to keep its tail visible. Defaults to 128px@@ -552,11 +543,7 @@ const Conversations = ({};}, [composerModelOverride]);- const shareAgentName = 'OpenHuman';- const textInputRef = useRef<HTMLTextAreaElement>(null);- const composerFooterRef = useRef<HTMLDivElement>(null);- const isComposingTextRef = useRef(false);// One-shot guard for the Stop/ESC partial-preservation path (#4862): request// ids whose partial reply has already been persisted, so a repeated Stop/ESC// fired before the `cancelled` event clears the live stream can't append the@@ -566,11 +553,6 @@ const Conversations = ({// thread. Per-thread (a Set) so a send to thread B isn't blocked by an// in-flight send to thread A.const pendingSendsRef = useRef<Set<string>>(new Set());- const mediaRecorderRef = useRef<MediaRecorder | null>(null);- const mediaStreamRef = useRef<MediaStream | null>(null);- const audioChunksRef = useRef<Blob[]>([]);- const replyAudioRef = useRef<HTMLAudioElement | null>(null);- const lastSpokenMessageIdRef = useRef<string | null>(null);// Per-thread silence timers. Each in-flight turn gets its own 120s safety// timer keyed by thread id, so concurrent turns on different threads don't// share (and clobber) a single timeout.@@ -597,18 +579,6 @@ const Conversations = ({// foreground turn's timer alive.const turnSignatureByThreadRef = useRef<Map<string, readonly unknown[]>>(new Map());- const getAudioExtension = (mimeType: string): string => {- const lower = mimeType.toLowerCase();- if (lower.includes('webm')) return 'webm';- if (lower.includes('ogg')) return 'ogg';- if (lower.includes('wav')) return 'wav';- if (lower.includes('mp4') || lower.includes('mpeg') || lower.includes('aac')) return 'm4a';- return 'webm';- };- const canUseMicrophoneApi =- typeof navigator !== 'undefined' &&- typeof navigator.mediaDevices !== 'undefined' &&- typeof navigator.mediaDevices.getUserMedia === 'function';const handleCreateNewThread = async () => {try {@@ -794,7 +764,6 @@ const Conversations = ({return;}- setInputMode('text');setInputValue(prev => {const base = prev.trim();if (!base) return text;@@ -1001,55 +970,7 @@ const Conversations = ({inferenceHeartbeatByThread,]);- useEffect(() => {- return () => {- mediaRecorderRef.current?.stop();- mediaStreamRef.current?.getTracks().forEach(track => track.stop());- replyAudioRef.current?.pause();- replyAudioRef.current = null;- };- }, []);-- useEffect(() => {- if (inputMode === 'text' && isRecording) {- mediaRecorderRef.current?.stop();- }- }, [inputMode, isRecording]);-- useEffect(() => {- if (inputMode === 'voice') {- setReplyMode('voice');- } else if (replyMode === 'voice') {- setReplyMode('text');- }- }, [inputMode, replyMode]);- // Proactively check voice binary availability when switching to voice mode- useEffect(() => {- if (inputMode !== 'voice' || !rustChat) return;- let cancelled = false;- void (async () => {- try {- const status = await openhumanVoiceStatus();- if (cancelled) return;- if (!status.stt_available) {- setVoiceStatus(- status.stt_error ??- 'Voice input needs a working speech-to-text engine. Pick one in Settings > Voice.'- );- } else {- setVoiceStatus('Ready — tap "Start Talking" to record.');- }- } catch {- if (!cancelled) {- setVoiceStatus('Could not check voice availability.');- }- }- })();- return () => {- cancelled = true;- };- }, [inputMode, rustChat]);const handleSlashCommand = (command: string): boolean => {const decision = handleComposerSlashCommand(command);@@ -1316,81 +1237,6 @@ const Conversations = ({handleSendMessageRef.current = handleSendMessage;- // Send a PARALLEL (forked) turn on the selected thread — runs concurrently- // with the in-flight turn instead of interrupting it (queue_mode 'parallel').- // Kept separate from `handleSendMessage` so it never touches the primary- // turn's lifecycle (silence timer, active marker, pending guard); the forked- // turn streams into its own lane (registered via `registerParallelRequest`)- // and renders as an interleaved branch bubble.- const handleSendParallel = async (text?: string) => {- if (!rustChat || !selectedThreadId) return;- const threadId = selectedThreadId;- const normalized = (text ?? inputValue).trim();- if (!normalized && attachments.length === 0) return;-- const pendingAttachments = attachments.slice();- const modelOverride = composerModelOverride ?? CHAT_MODEL_HINT;- const messageText = buildMessageWithAttachments(normalized, pendingAttachments);- const userMessage: ThreadMessage = {- id: `msg_${globalThis.crypto.randomUUID()}`,- content: normalized,- type: 'text',- extraMetadata:- pendingAttachments.length > 0- ? {- attachmentCount: pendingAttachments.length,- attachmentNames: pendingAttachments.map(a => a.file.name),- attachmentKinds: pendingAttachments.map(a => a.kind),- attachmentDataUris: pendingAttachments- .filter(a => a.kind === 'image')- .map(a => a.previewUri ?? a.dataUri),- // Poster (first frame) per attachment, index-aligned with- // attachmentKinds — only video entries carry one; others null.- attachmentPosters: pendingAttachments.map(a =>- a.kind === 'video' ? (a.previewUri ?? a.dataUri) : null- ),- attachmentCompressed: pendingAttachments.map(a => a.compressed),- parallelBranch: true,- }- : { parallelBranch: true },- sender: 'user',- createdAt: new Date().toISOString(),- };-- try {- await dispatch(addMessageLocal({ threadId, message: userMessage })).unwrap();- } catch (error) {- if (error === THREAD_NOT_FOUND_MESSAGE) return;- const msg = error instanceof Error ? error.message : String(error);- setSendError(chatSendError('cloud_send_failed', msg));- return;- }-- setInputValue('');- setAttachments([]);- setSendError(null);-- try {- const requestId = await chatSend({- threadId,- message: messageText,- model: modelOverride,- locale: uiLocale,- queueMode: 'parallel',- });- if (requestId) {- dispatch(registerParallelRequest({ threadId, requestId }));- }- trackAnalyticsEvent('chat_message_sent', {- send_mode: 'parallel',- has_attachments: pendingAttachments.length > 0,- });- } catch (err) {- const msg = err instanceof Error ? err.message : String(err);- setSendError(chatSendError('cloud_send_failed', msg));- setInputValue(normalized);- }- };// Queue a FOLLOW-UP on the selected thread while a turn is streaming// (queue_mode 'followup'): the backend sends it as a fresh turn once the@@ -1575,175 +1421,6 @@ const Conversations = ({true);- const transcribeAndSendAudio = async (mimeType: string) => {- setIsRecording(false);- mediaRecorderRef.current = null;- mediaStreamRef.current?.getTracks().forEach(track => track.stop());- mediaStreamRef.current = null;-- const chunks = audioChunksRef.current;- audioChunksRef.current = [];- if (chunks.length === 0) {- notifyOverlaySttState('cancelled');- setVoiceStatus('No audio captured. Try again.');- return;- }-- setIsTranscribing(true);- setVoiceStatus('Transcribing…');- try {- const blob = new Blob(chunks, { type: mimeType || 'audio/webm' });- const audioBytes = Array.from(new Uint8Array(await blob.arrayBuffer()));- const extension = getAudioExtension(mimeType || blob.type);-- // Build conversation context from recent messages for LLM cleanup.- const recentMessages = messages.slice(-10);- const context =- recentMessages.length > 0- ? recentMessages.map(m => `${m.sender}: ${m.content}`).join('\n')- : undefined;-- const result = await openhumanVoiceTranscribeBytes(audioBytes, extension, context);- const transcript = result.text.trim();-- if (!transcript) {- notifyOverlaySttState('cancelled');- setVoiceStatus('No speech detected. Try again.');- return;- }-- notifyOverlaySttState('transcription_done', transcript);- setVoiceStatus(`Heard: ${transcript}`);- await handleSendMessage(transcript);- } catch (err) {- notifyOverlaySttState('error');- const message = err instanceof Error ? err.message : String(err);- const isSetupIssue =- message.includes('no voice provider') ||- message.includes('binary not found') ||- message.includes('sign in first');- setSendError(- chatSendError(- isSetupIssue ? 'stt_not_ready' : 'voice_transcription',- isSetupIssue- ? 'Voice input needs a working speech-to-text engine. Set one up in Settings > Voice.'- : `Voice transcription failed: ${message}`- )- );- setVoiceStatus(null);- } finally {- setIsTranscribing(false);- }- };-- const handleVoiceRecordToggle = async () => {- if (!rustChat || selectedThreadActive || isTranscribing) return;- if (!canUseMicrophoneApi) {- setSendError(- chatSendError(- 'microphone_unavailable',- 'Microphone capture is unavailable in this runtime. Use Text mode, or run the desktop app bundle with microphone permissions enabled.'- )- );- return;- }-- if (isRecording) {- mediaRecorderRef.current?.stop();- return;- }-- try {- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });- mediaStreamRef.current = stream;-- const preferredTypes = [- 'audio/webm;codecs=opus',- 'audio/webm',- 'audio/ogg;codecs=opus',- 'audio/ogg',- 'audio/mp4',- ];- const supportedType = preferredTypes.find(type => MediaRecorder.isTypeSupported(type));- const recorder = supportedType- ? new MediaRecorder(stream, { mimeType: supportedType })- : new MediaRecorder(stream);-- audioChunksRef.current = [];- recorder.ondataavailable = event => {- if (event.data.size > 0) {- audioChunksRef.current.push(event.data);- }- };- recorder.onerror = () => {- notifyOverlaySttState('error');- setIsRecording(false);- mediaStreamRef.current?.getTracks().forEach(track => track.stop());- mediaStreamRef.current = null;- setSendError(chatSendError('microphone_recording', 'Microphone recording failed.'));- };- recorder.onstop = () => {- void transcribeAndSendAudio(recorder.mimeType);- };-- mediaRecorderRef.current = recorder;- setVoiceStatus('Listening… click Stop to send.');- setSendError(null);- setIsRecording(true);- recorder.start();- notifyOverlaySttState('recording_started');- } catch (err) {- notifyOverlaySttState('error');- const message = err instanceof Error ? err.message : String(err);- setSendError(chatSendError('microphone_access', `Microphone access failed: ${message}`));- setVoiceStatus(null);- }- };-- useEffect(() => {- const latestAgentMessage = [...messages].reverse().find(m => m.sender === 'agent');- if (!latestAgentMessage) return;-- if (replyMode === 'text') {- lastSpokenMessageIdRef.current = latestAgentMessage.id;- replyAudioRef.current?.pause();- replyAudioRef.current = null;- setIsPlayingReply(false);- return;- }-- if (!rustChat || latestAgentMessage.id === lastSpokenMessageIdRef.current) return;-- lastSpokenMessageIdRef.current = latestAgentMessage.id;- let cancelled = false;- setIsPlayingReply(true);-- void (async () => {- try {- const ttsResult = await openhumanVoiceTts(latestAgentMessage.content);- if (cancelled) return;-- const audioSrc = convertFileSrc(ttsResult.output_path);- const audio = new window.Audio(audioSrc);- replyAudioRef.current?.pause();- replyAudioRef.current = audio;-- await audio.play();- } catch {- if (!cancelled) {- setSendError(chatSendError('voice_playback', 'Failed to play voice reply.'));- }- } finally {- if (!cancelled) {- setIsPlayingReply(false);- }- }- })();-- return () => {- cancelled = true;- };- }, [messages, replyMode, rustChat]);const handleComposerEscape = useCallback(() => {if (!selectedThreadActive) return;@@ -1776,45 +1453,6 @@ const Conversations = ({}}, [handleStopGeneration, inputValue, messages, selectedThreadActive, selectedThreadId]);- const handleInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {- if (isComposingTextRef.current || isImeCompositionKeyEvent(e)) return;-- // ESC while the selected thread is streaming interrupts the turn AND- // restores the user's last prompt into the composer for re-editing in- // place (#4862). Interrupt always fires; the prompt is only re-hydrated- // when the composer is empty so a follow-up the user already started- // typing is never clobbered. When nothing is streaming, ESC is left to its- // default behaviour (blur / no-op).- if (e.key === 'Escape' && selectedThreadActive) {- e.preventDefault();- handleComposerEscape();- return;- }-- // Cmd/Ctrl+Enter sends a PARALLEL branch when the selected thread already- // has a turn in flight (otherwise it behaves like a normal send).- if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {- e.preventDefault();- if (selectedThreadActive) {- void handleSendParallel();- } else {- void handleSendMessage();- }- return;- }-- if (e.key === 'Enter' && !e.shiftKey) {- e.preventDefault();- // While the selected thread is streaming, a plain Enter queues a- // follow-up (sent after the current turn) instead of being blocked.- if (selectedThreadActive) {- void handleSendFollowup();- } else {- void handleSendMessage();- }- }- };-// NOTE: the transcript-local derivations that used to live here (copy,// sub-agent drawer, past-turn timelines, agent insights, streaming preview,// etc.) moved into `ChatThreadView` (`./components/ChatThreadView.tsx`),@@ -1887,41 +1525,6 @@ const Conversations = ({selectedThreadActive,rustChat,});- // Auto-focus the composer when a thread becomes selected and the composer- // isn't blocked. Without this, navigating into a thread from elsewhere in- // the app (e.g. acting on a subconscious reflection in the Intelligence- // tab — `IntelligenceSubconsciousTab.handleNavigateToReflectionThread`- // dispatches `setSelectedThread` then routes to `/chat`) leaves focus on- // the unmounted source button, falling back to `document.body`. The- // textarea is rendered and enabled but ignores keystrokes until the user- // clicks into it. Skip when there is no thread, when the composer is- // disabled, when in voice mode, and when the user has focus on another- // input/textarea/contenteditable (don't steal focus from a settings pane- // the user just clicked into).- useEffect(() => {- if (!selectedThreadId) return;- if (composerInteractionBlocked) return;- if (inputMode !== 'text') return;- const ta = textInputRef.current;- if (!ta) return;- const active = document.activeElement;- if (- active &&- active !== document.body &&- active !== ta &&- (active.tagName === 'INPUT' ||- active.tagName === 'TEXTAREA' ||- active.getAttribute('contenteditable') === 'true')- ) {- return;- }- // rAF — wait for the textarea to be in the layout tree (selectedThread- // changes can arrive a tick before the panel mounts on first navigation).- const id = window.requestAnimationFrame(() => {- textInputRef.current?.focus();- });- return () => window.cancelAnimationFrame(id);- }, [selectedThreadId, composerInteractionBlocked, inputMode]);const isSending = Boolean(selectedThreadId &&