Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions convex/groups/mutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
15 changes: 8 additions & 7 deletions packages/ui/src/chat/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
10 changes: 9 additions & 1 deletion packages/ui/src/chat/native/ChatThread.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
};
Expand Down
11 changes: 6 additions & 5 deletions packages/ui/src/chat/web/ChatThread.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ function AiBody({ message }: { message: ChatMessage }) {
const steps = ai.steps?.length ? <FinaiSteps steps={ai.steps} busy={busy} /> : null;
if (!message.text && busy)
return (
<span className={styles.aiThinking}>
<div className={styles.aiThinking}>
{steps}
{ai.steps?.some((step) => step.status === 'running') ? null : (
<ThinkingOrb
Expand All @@ -632,13 +632,13 @@ function AiBody({ message }: { message: ChatMessage }) {
caption={ai.stageLabel ?? 'Thinking…'}
/>
)}
</span>
</div>
);
return (
<>
<div>
{steps}
<FinaiMarkdown text={message.text ?? ''} streaming={ai.status === 'streaming'} />
</>
</div>
);
}

Expand All @@ -650,7 +650,7 @@ function Composer(c: ChatComposerProps) {
const [highlight, setHighlight] = React.useState(0);
const [dismissed, setDismissed] = React.useState<string | null>(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;
Expand All @@ -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);
Expand Down
74 changes: 55 additions & 19 deletions packages/ui/src/chat/web/voice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | null>(null);
Expand All @@ -41,17 +41,35 @@ export function useVoiceRecorder() {
const ticker = React.useRef<ReturnType<typeof setInterval> | 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(
() =>
Expand All @@ -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);
};
Expand All @@ -90,27 +116,37 @@ 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();
media.start(250);
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]);
Expand Down
10 changes: 9 additions & 1 deletion packages/ui/src/finance/native/GroupChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -352,6 +353,13 @@ export function GroupChatScreen(p: GroupChatScreenProps) {
{item.text}
</Typography>
)}
{item.audioUrl !== undefined && (
<VoiceBubble
src={item.audioUrl}
durationMs={item.durationMs}
mine={item.ownMessage}
/>
)}
{!!item.attachmentUrl && (
<Image
source={{ uri: item.attachmentUrl }}
Expand All @@ -360,7 +368,7 @@ export function GroupChatScreen(p: GroupChatScreenProps) {
style={{ width: 210, maxWidth: '100%', height: 170, borderRadius: 6 }}
/>
)}
{!item.text && !item.attachmentUrl && (
{!item.text && !item.attachmentUrl && item.audioUrl === undefined && (
<Typography variant="caption">
Bill image is no longer available.
</Typography>
Expand Down
12 changes: 10 additions & 2 deletions packages/ui/src/finance/web/GroupChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -299,7 +300,14 @@ export function GroupChatScreen(p: GroupChatScreenProps) {
<div className={s.bubble}>
{item.kind === 'message' ? (
<>
{item.text && <p>{item.text}</p>}
{!!item.text && <span>{item.text}</span>}
{item.audioUrl !== undefined && (
<VoiceBubble
src={item.audioUrl}
durationMs={item.durationMs}
mine={item.ownMessage}
/>
)}
{item.attachmentUrl && (
<a href={item.attachmentUrl} target="_blank" rel="noreferrer">
<img
Expand All @@ -309,7 +317,7 @@ export function GroupChatScreen(p: GroupChatScreenProps) {
/>
</a>
)}
{!item.text && !item.attachmentUrl && (
{!item.text && !item.attachmentUrl && item.audioUrl === undefined && (
<span className={s.muted}>Bill image is no longer available.</span>
)}
</>
Expand Down
56 changes: 55 additions & 1 deletion tests/convex/voice-and-retention.test.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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', () => {
Expand Down
Loading