From ab9d10bef561805d989e273a65ae80a330a84ff9 Mon Sep 17 00:00:00 2001 From: NeerajCodz Date: Fri, 27 Nov 2026 07:41:36 +0530 Subject: [PATCH 1/3] fix(chat): stabilize voice and message flows - Guard recorder lifecycle races and restore group-chat message behavior. - Fixes #204, #205, #206, #207, #208, #210, #211, and #212. --- convex/groups/mutations.ts | 16 ++++ packages/ui/src/chat/hooks.ts | 15 ++-- packages/ui/src/chat/native/ChatThread.tsx | 10 ++- packages/ui/src/chat/web/ChatThread.tsx | 11 +-- packages/ui/src/chat/web/voice.tsx | 74 ++++++++++++++----- .../ui/src/finance/native/GroupChatScreen.tsx | 20 +++-- .../ui/src/finance/web/GroupChatScreen.tsx | 18 ++++- tests/convex/voice-and-retention.test.ts | 56 +++++++++++++- 8 files changed, 178 insertions(+), 42 deletions(-) diff --git a/convex/groups/mutations.ts b/convex/groups/mutations.ts index 982d79f3..258b4c47 100644 --- a/convex/groups/mutations.ts +++ b/convex/groups/mutations.ts @@ -1334,6 +1334,22 @@ export const deleteExpiredMessage = internalMutation({ handler: async (ctx, { messageId }) => { const message = await ctx.db.get(messageId); if (!message || message.expiresAt === undefined) return; + const group = await ctx.db.get(message.groupId); + const currentExpiresAt = !group + ? message.expiresAt + : group.messageRetentionMs == null + ? undefined + : message.createdAt + group.messageRetentionMs; + if (currentExpiresAt !== message.expiresAt) { + await ctx.db.patch(messageId, { expiresAt: currentExpiresAt }); + if (currentExpiresAt !== undefined) + await ctx.scheduler.runAt( + Math.max(Date.now(), currentExpiresAt), + internal.groups.mutations.deleteExpiredMessage, + { messageId }, + ); + return; + } if (message.expiresAt > Date.now()) { await ctx.scheduler.runAt(message.expiresAt, internal.groups.mutations.deleteExpiredMessage, { messageId, diff --git a/packages/ui/src/chat/hooks.ts b/packages/ui/src/chat/hooks.ts index 72e76ae9..815c966a 100644 --- a/packages/ui/src/chat/hooks.ts +++ b/packages/ui/src/chat/hooks.ts @@ -98,13 +98,14 @@ type PendingSend = { */ /** Releases a local preview (`blob:` URL) once its pending message is gone. */ function releasePreview(message: ChatMessage | undefined) { - const url = message?.imageUrl; - if ( - typeof url === 'string' && - url.startsWith('blob:') && - typeof URL.revokeObjectURL === 'function' - ) - URL.revokeObjectURL(url); + for (const url of [message?.imageUrl, message?.audioUrl]) { + if ( + typeof url === 'string' && + url.startsWith('blob:') && + typeof URL.revokeObjectURL === 'function' + ) + URL.revokeObjectURL(url); + } } export function useOptimisticMessages(onError?: (error: unknown) => void) { diff --git a/packages/ui/src/chat/native/ChatThread.tsx b/packages/ui/src/chat/native/ChatThread.tsx index 6d9b75cb..dd8df029 100644 --- a/packages/ui/src/chat/native/ChatThread.tsx +++ b/packages/ui/src/chat/native/ChatThread.tsx @@ -862,7 +862,15 @@ function Composer(c: ChatComposerProps) { const active = c.mentions?.length ? activeMention(c.draft, caret) : null; const options = active ? mentionMatches(c.mentions!, active.query) : []; const insertEmoji = (emoji: string) => { - const next = insertAtCaret(c.draft, emoji, caret); + let remaining = CHAT_TEXT_LIMIT - c.draft.length; + let boundedEmoji = ''; + for (const character of emoji) { + if (character.length > remaining) break; + boundedEmoji += character; + remaining -= character.length; + } + if (!boundedEmoji) return; + const next = insertAtCaret(c.draft, boundedEmoji, caret); c.onDraftChange(next.draft); setSelection({ start: next.caret, end: next.caret }); }; diff --git a/packages/ui/src/chat/web/ChatThread.tsx b/packages/ui/src/chat/web/ChatThread.tsx index 34054e5a..ca453538 100644 --- a/packages/ui/src/chat/web/ChatThread.tsx +++ b/packages/ui/src/chat/web/ChatThread.tsx @@ -622,7 +622,7 @@ function AiBody({ message }: { message: ChatMessage }) { const steps = ai.steps?.length ? : null; if (!message.text && busy) return ( - +
{steps} {ai.steps?.some((step) => step.status === 'running') ? null : ( )} - +
); return ( - <> +
{steps} - +
); } @@ -650,7 +650,7 @@ function Composer(c: ChatComposerProps) { const [highlight, setHighlight] = React.useState(0); const [dismissed, setDismissed] = React.useState(null); const [emojiOpen, setEmojiOpen] = React.useState(false); - const recorder = useVoiceRecorder(); + const recorder = useVoiceRecorder(c.onSendVoice); const recording = recorder.state === 'recording'; // With nothing typed the action button records a voice message instead of sending. const showMic = !!c.onSendVoice && !c.draft.trim() && !recording; @@ -671,6 +671,7 @@ function Composer(c: ChatComposerProps) { focusAt(next.caret); }; const insertEmoji = (emoji: string) => { + if (c.draft.length + emoji.length > CHAT_TEXT_LIMIT) return; const next = insertAtCaret(c.draft, emoji, caret); c.onDraftChange(next.draft); setCaret(next.caret); diff --git a/packages/ui/src/chat/web/voice.tsx b/packages/ui/src/chat/web/voice.tsx index bcf584ac..4d5da65d 100644 --- a/packages/ui/src/chat/web/voice.tsx +++ b/packages/ui/src/chat/web/voice.tsx @@ -31,7 +31,7 @@ export function voiceRecordingSupported(): boolean { * Records one clip at a time. `stop()` resolves with the clip (null if it was too short or * cancelled). Recording stops by itself at the maximum length. */ -export function useVoiceRecorder() { +export function useVoiceRecorder(onAutoStop?: (clip: VoiceClip) => void) { const [state, setState] = React.useState<'idle' | 'recording'>('idle'); const [elapsedMs, setElapsedMs] = React.useState(0); const [error, setError] = React.useState(null); @@ -41,17 +41,35 @@ export function useVoiceRecorder() { const ticker = React.useRef | null>(null); const settle = React.useRef<((clip: VoiceClip | null) => void) | null>(null); const cancelled = React.useRef(false); - + const autoStopped = React.useRef(false); + const mounted = React.useRef(false); + const startRequest = React.useRef(0); + const onAutoStopRef = React.useRef(onAutoStop); + onAutoStopRef.current = onAutoStop; const cleanup = React.useCallback(() => { - if (ticker.current) clearInterval(ticker.current); - ticker.current = null; + if (ticker.current !== null) { + clearInterval(ticker.current); + ticker.current = null; + } recorder.current?.stream.getTracks().forEach((track) => track.stop()); recorder.current = null; - setState('idle'); - setElapsedMs(0); + if (mounted.current) { + setState('idle'); + setElapsedMs(0); + } }, []); - React.useEffect(() => () => cleanup(), [cleanup]); + React.useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + startRequest.current += 1; + cancelled.current = true; + cleanup(); + settle.current?.(null); + settle.current = null; + }; + }, [cleanup]); const stop = React.useCallback( () => @@ -73,12 +91,20 @@ export function useVoiceRecorder() { setError('Voice messages aren’t supported in this browser.'); return false; } + const request = ++startRequest.current; + let pendingStream: MediaStream | null = null; try { - const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); + pendingStream = await navigator.mediaDevices.getUserMedia({ audio: true }); + if (!mounted.current || request !== startRequest.current) { + pendingStream.getTracks().forEach((track) => track.stop()); + return false; + } const type = pickRecordingType(); - const media = new MediaRecorder(stream, type ? { mimeType: type } : undefined); + const media = new MediaRecorder(pendingStream, type ? { mimeType: type } : undefined); + pendingStream = null; chunks.current = []; cancelled.current = false; + autoStopped.current = false; media.ondataavailable = (event) => { if (event.data.size) chunks.current.push(event.data); }; @@ -90,9 +116,14 @@ export function useVoiceRecorder() { cancelled.current || durationMs < VOICE_MIN_DURATION_MS || !blob.size ? null : { blob, durationMs: Math.min(durationMs, VOICE_MAX_DURATION_MS), mimeType }; + const wasAutoStopped = autoStopped.current; cleanup(); - settle.current?.(clip); - settle.current = null; + if (settle.current) { + settle.current(clip); + settle.current = null; + } else if (wasAutoStopped && clip && mounted.current) { + onAutoStopRef.current?.(clip); + } }; recorder.current = media; startedAt.current = Date.now(); @@ -100,17 +131,22 @@ export function useVoiceRecorder() { setState('recording'); ticker.current = setInterval(() => { const elapsed = Date.now() - startedAt.current; - setElapsedMs(elapsed); - if (elapsed >= VOICE_MAX_DURATION_MS) media.stop(); + if (mounted.current) setElapsedMs(elapsed); + if (elapsed >= VOICE_MAX_DURATION_MS && media.state !== 'inactive') { + autoStopped.current = true; + media.stop(); + } }, 200); return true; } catch (cause) { - cleanup(); - setError( - cause instanceof DOMException && cause.name === 'NotAllowedError' - ? 'Allow microphone access to record a voice message.' - : 'Could not start recording.', - ); + pendingStream?.getTracks().forEach((track) => track.stop()); + if (request === startRequest.current) cleanup(); + if (mounted.current && request === startRequest.current) + setError( + cause instanceof DOMException && cause.name === 'NotAllowedError' + ? 'Allow microphone access to record a voice message.' + : 'Could not start recording.', + ); return false; } }, [cleanup]); diff --git a/packages/ui/src/finance/native/GroupChatScreen.tsx b/packages/ui/src/finance/native/GroupChatScreen.tsx index 07935d21..d734234a 100644 --- a/packages/ui/src/finance/native/GroupChatScreen.tsx +++ b/packages/ui/src/finance/native/GroupChatScreen.tsx @@ -30,6 +30,7 @@ import { type ChatReactionEmoji, } from '../../chat/model'; import type { NativeVoiceClip } from '../../chat/native/voice'; +import { VoiceBubble } from '../../chat/native/voice'; export type GroupChatItem = { id: string; @@ -352,6 +353,13 @@ export function GroupChatScreen(p: GroupChatScreenProps) { {item.text} )} + {item.audioUrl !== undefined && ( + + )} {!!item.attachmentUrl && ( )} - {!item.text && !item.attachmentUrl && ( - - Bill image is no longer available. - - )} + {!item.text && + !item.attachmentUrl && + item.audioUrl === undefined && ( + + Bill image is no longer available. + + )} ) : ( {item.kind === 'message' ? ( <> - {item.text &&

{item.text}

} + {!!item.text && {item.text}} + {item.audioUrl !== undefined && ( + + )} {item.attachmentUrl && ( )} - {!item.text && !item.attachmentUrl && ( - Bill image is no longer available. - )} + {!item.text && + !item.attachmentUrl && + item.audioUrl === undefined && ( + Bill image is no longer available. + )} ) : item.onPress ? (