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..fb257596 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 && ( + {!item.text && !item.attachmentUrl && item.audioUrl === undefined && ( Bill image is no longer available. diff --git a/packages/ui/src/finance/web/GroupChatScreen.tsx b/packages/ui/src/finance/web/GroupChatScreen.tsx index ec901f5c..572b78f2 100644 --- a/packages/ui/src/finance/web/GroupChatScreen.tsx +++ b/packages/ui/src/finance/web/GroupChatScreen.tsx @@ -24,6 +24,7 @@ import { type ChatReactionEmoji, } from '../../chat/model'; import type { VoiceClip } from '../../chat/web/voice'; +import { VoiceBubble } from '../../chat/web/voice'; export type GroupChatItem = { id: string; @@ -299,7 +300,14 @@ export function GroupChatScreen(p: GroupChatScreenProps) { {item.kind === 'message' ? ( <> - {item.text && {item.text}} + {!!item.text && {item.text}} + {item.audioUrl !== undefined && ( + + )} {item.attachmentUrl && ( )} - {!item.text && !item.attachmentUrl && ( + {!item.text && !item.attachmentUrl && item.audioUrl === undefined && ( Bill image is no longer available. )} > diff --git a/tests/convex/voice-and-retention.test.ts b/tests/convex/voice-and-retention.test.ts index 4d87e89b..20416007 100644 --- a/tests/convex/voice-and-retention.test.ts +++ b/tests/convex/voice-and-retention.test.ts @@ -1,6 +1,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { convexTest } from 'convex-test'; -import { api } from '../../convex/_generated/api'; +import { api, internal } from '../../convex/_generated/api'; import schema from '../../convex/schema'; import { chatHeaderSubtitle, recordTime } from '../../packages/ui/src/chat/model'; @@ -177,6 +177,60 @@ describe('disappearing messages', () => { expect(messages).toHaveLength(450); expect(messages.every((m) => m.expiresAt === m.createdAt + DAY)).toBe(true); }); + + it('retimes a stale expiry job when retention is lengthened', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-01T00:00:00Z')); + const { t, ids, owner } = await seed(DAY); + const createdAt = Date.now() - DAY - 1; + const messageId = await t.run((ctx) => + ctx.db.insert('groupMessages', { + groupId: ids.groupId, + senderId: ids.memberId, + kind: 'text', + text: 'keep me', + createdAt, + expiresAt: Date.now() - 1, + }), + ); + + await owner.mutation(api.groups.mutations.updateSettings, { + groupId: ids.groupId, + messageRetentionMs: 30 * DAY, + }); + await t.mutation(internal.groups.mutations.deleteExpiredMessage, { messageId }); + + expect(await t.run((ctx) => ctx.db.get(messageId))).toMatchObject({ + text: 'keep me', + expiresAt: createdAt + 30 * DAY, + }); + }); + + it('clears stale expiry metadata when retention is disabled', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-03-01T00:00:00Z')); + const { t, ids, owner } = await seed(DAY); + const messageId = await t.run((ctx) => + ctx.db.insert('groupMessages', { + groupId: ids.groupId, + senderId: ids.memberId, + kind: 'text', + text: 'keep me', + createdAt: Date.now() - DAY - 1, + expiresAt: Date.now() - 1, + }), + ); + + await owner.mutation(api.groups.mutations.updateSettings, { + groupId: ids.groupId, + messageRetentionMs: null, + }); + await t.mutation(internal.groups.mutations.deleteExpiredMessage, { messageId }); + + const message = await t.run((ctx) => ctx.db.get(messageId)); + expect(message).toMatchObject({ text: 'keep me' }); + expect(message?.expiresAt).toBeUndefined(); + }); }); describe('chat helpers', () => {
{item.text}