diff --git a/apps/mobile/hooks/useFinaiActivity.ts b/apps/mobile/hooks/useFinaiActivity.ts index 2b596c15..92a0980d 100644 --- a/apps/mobile/hooks/useFinaiActivity.ts +++ b/apps/mobile/hooks/useFinaiActivity.ts @@ -10,34 +10,33 @@ import { finaiViewing, shouldToastReply, type FinaiLatestReply } from '@finapp/u */ export function useFinaiActivity(enabled: boolean, onReply: (reply: FinaiLatestReply) => void) { const activity = useQuery(api.ai.assistant.activity, enabled ? {} : 'skip'); - const seenAt = React.useRef(null); + const seenReplyIds = React.useRef | null>(null); const onReplyRef = React.useRef(onReply); React.useEffect(() => { onReplyRef.current = onReply; }); - const latest = React.useMemo( - () => - activity?.latest - ? { - ...activity.latest, - conversationId: String(activity.latest.conversationId), - replyId: String(activity.latest.replyId), - } - : null, - [activity], - ); - const latestAt = latest?.at ?? 0; React.useEffect(() => { - if (!activity) return; - if (seenAt.current === null) { - seenAt.current = Math.max(latestAt, Date.now() - 1_000); + if (!activity) { + seenReplyIds.current = null; return; } - if (latest && shouldToastReply(latest, seenAt.current, finaiViewing())) - onReplyRef.current(latest); - seenAt.current = Math.max(seenAt.current, latestAt); - }, [activity, latest, latestAt]); + if (seenReplyIds.current === null) { + seenReplyIds.current = new Set(activity.replies.map((reply) => String(reply.replyId))); + return; + } + for (const reply of activity.replies) { + const replyId = String(reply.replyId); + if (seenReplyIds.current.has(replyId)) continue; + seenReplyIds.current.add(replyId); + const latest: FinaiLatestReply = { + ...reply, + conversationId: String(reply.conversationId), + replyId, + }; + if (shouldToastReply(latest, -1, finaiViewing())) onReplyRef.current(latest); + } + }, [activity]); return { working: activity?.working ?? false, diff --git a/apps/web/components/finance/FinaiLauncher.tsx b/apps/web/components/finance/FinaiLauncher.tsx index 62f78e9b..950d5774 100644 --- a/apps/web/components/finance/FinaiLauncher.tsx +++ b/apps/web/components/finance/FinaiLauncher.tsx @@ -19,12 +19,17 @@ import { useFinaiActivity } from '@/lib/finai/useFinaiActivity'; */ export function FinaiLauncher() { const pathname = usePathname(); + const onFinaiPage = pathname === '/finai' || pathname.startsWith('/finai/'); const { userId, isConnected } = useBrowserSync(); const [open, setOpen] = React.useState(false); const panelRef = React.useRef(null); const buttonRef = React.useRef(null); // Phones show the chat full screen: that is a modal and must hold focus. const [fullScreen, setFullScreen] = React.useState(false); + + React.useEffect(() => { + if (onFinaiPage) setOpen(false); + }, [onFinaiPage]); React.useEffect(() => { const query = window.matchMedia('(max-width: 767px)'); const update = () => setFullScreen(query.matches); @@ -32,33 +37,36 @@ export function FinaiLauncher() { query.addEventListener('change', update); return () => query.removeEventListener('change', update); }, []); - const live = Boolean(userId && isConnected && open); + const live = Boolean(userId && isConnected && open && !onFinaiPage); const finaiSettings = useQuery(api.ai.settings.get, userId && isConnected ? {} : 'skip'); const assistant = useFinaiAssistant(live); const decide = useFinaiDecide(); const router = useRouter(); - const onFinaiPage = pathname === '/finai' || pathname.startsWith('/finai/'); const { select } = assistant; // Replies keep going after the chat is closed: say when one lands somewhere off screen. - const activity = useFinaiActivity(Boolean(userId && isConnected), (reply) => { - toast(reply.failed ? 'FinAI couldn’t finish a reply' : 'FinAI replied', { - description: reply.failed ? reply.title : reply.preview || reply.title, - action: { - label: 'Open', - onClick: () => { - if (onFinaiPage) { - router.push(`/finai?c=${encodeURIComponent(reply.conversationId)}`); - return; - } - select(reply.conversationId); - setOpen(true); + const activity = useFinaiActivity( + Boolean(userId && isConnected), + (reply) => { + toast(reply.failed ? 'FinAI couldn’t finish a reply' : 'FinAI replied', { + description: reply.failed ? reply.title : reply.preview || reply.title, + action: { + label: 'Open', + onClick: () => { + if (onFinaiPage) { + router.push(`/finai?c=${encodeURIComponent(reply.conversationId)}`); + return; + } + select(reply.conversationId); + setOpen(true); + }, }, - }, - }); - }); + }); + }, + userId ? String(userId) : null, + ); React.useEffect(() => { - if (!open) return; + if (!open || onFinaiPage) return; const button = buttonRef.current; const panel = panelRef.current; // Move focus into the chat (its message box) when it opens. @@ -94,7 +102,7 @@ export function FinaiLauncher() { // Back to the launcher (visible again once the panel closes). requestAnimationFrame(() => button?.focus()); }; - }, [fullScreen, open]); + }, [fullScreen, onFinaiPage, open]); if (!userId || onFinaiPage) return null; if (finaiSettings && (!finaiSettings.enabled || !finaiSettings.showLauncher)) return null; diff --git a/apps/web/lib/finai/activityTracker.ts b/apps/web/lib/finai/activityTracker.ts new file mode 100644 index 00000000..1882488c --- /dev/null +++ b/apps/web/lib/finai/activityTracker.ts @@ -0,0 +1,39 @@ +import type { FinaiLatestReply } from '@finapp/ui/ai/finai'; + +export type FinaiActivityTracker = { + userId: string | null; + seenReplyIds: Set | null; +}; + +type ActivitySnapshot = { replies: readonly FinaiLatestReply[] }; + +export function collectUnseenReplies( + tracker: FinaiActivityTracker, + userId: string | null, + activity: ActivitySnapshot | undefined, +): FinaiLatestReply[] { + if (tracker.userId !== userId) { + tracker.userId = userId; + tracker.seenReplyIds = null; + } + if (!activity) return []; + + const seenReplyIds = tracker.seenReplyIds; + if (seenReplyIds === null) { + tracker.seenReplyIds = new Set(activity.replies.map((reply) => String(reply.replyId))); + return []; + } + + const unseen: FinaiLatestReply[] = []; + for (const reply of activity.replies) { + const replyId = String(reply.replyId); + if (seenReplyIds.has(replyId)) continue; + seenReplyIds.add(replyId); + unseen.push({ + ...reply, + conversationId: String(reply.conversationId), + replyId, + }); + } + return unseen; +} diff --git a/apps/web/lib/finai/useFinaiActivity.ts b/apps/web/lib/finai/useFinaiActivity.ts index 486ecdd5..9de9a0f9 100644 --- a/apps/web/lib/finai/useFinaiActivity.ts +++ b/apps/web/lib/finai/useFinaiActivity.ts @@ -4,42 +4,30 @@ import * as React from 'react'; import { useQuery } from 'convex/react'; import { api } from '@convex/_generated/api'; import { finaiViewing, shouldToastReply, type FinaiLatestReply } from '@finapp/ui/ai/finai'; +import { collectUnseenReplies, type FinaiActivityTracker } from './activityTracker'; /** * FinAI replies keep going after the chat is closed. This watches for them: `working` while a * reply is being written, `unreadCount` chats with unseen replies, and `onReply` for each newly * finished reply whose chat isn't on screen (never for replies that finished before mount). */ -export function useFinaiActivity(enabled: boolean, onReply: (reply: FinaiLatestReply) => void) { +export function useFinaiActivity( + enabled: boolean, + onReply: (reply: FinaiLatestReply) => void, + userId: string | null, +) { const activity = useQuery(api.ai.assistant.activity, enabled ? {} : 'skip'); - const seenAt = React.useRef(null); + const tracker = React.useRef({ userId, seenReplyIds: null }); const onReplyRef = React.useRef(onReply); React.useEffect(() => { onReplyRef.current = onReply; }); - const latest = React.useMemo( - () => - activity?.latest - ? { - ...activity.latest, - conversationId: String(activity.latest.conversationId), - replyId: String(activity.latest.replyId), - } - : null, - [activity], - ); - const latestAt = latest?.at ?? 0; React.useEffect(() => { - if (!activity) return; - if (seenAt.current === null) { - seenAt.current = Math.max(latestAt, Date.now() - 1_000); - return; + for (const latest of collectUnseenReplies(tracker.current, userId, activity)) { + if (shouldToastReply(latest, -1, finaiViewing())) onReplyRef.current(latest); } - if (latest && shouldToastReply(latest, seenAt.current, finaiViewing())) - onReplyRef.current(latest); - seenAt.current = Math.max(seenAt.current, latestAt); - }, [activity, latest, latestAt]); + }, [activity, userId]); return { working: activity?.working ?? false, diff --git a/convex/ai/assistant.ts b/convex/ai/assistant.ts index 8ddc00d7..1b57d551 100644 --- a/convex/ai/assistant.ts +++ b/convex/ai/assistant.ts @@ -67,18 +67,28 @@ const REPLY_STALE_MS = 6 * 60_000; function isWorking(row: Doc<'finaiConversations'>, now: number) { return row.working === true && now - row.updatedAt < REPLY_STALE_MS; + } +/** Publishes the stale-work transition so subscribed queries rerun at the cutoff. */ +export const expireAbandoned = internalMutation({ + args: { conversationId: v.id('finaiConversations'), updatedAt: v.number() }, + handler: async (ctx, { conversationId, updatedAt }) => { + const row = await ctx.db.get(conversationId); + if (row?.working === true && row.updatedAt === updatedAt) + await ctx.db.patch(conversationId, { working: false }); + }, +}); /** * FinAI activity for the launcher, tabs and sidebar: whether a reply is being written, how many - * chats have unseen replies, and the newest finished reply (clients toast it when it changes and - * that chat isn't on screen). Replies keep going after the chat is closed. + * chats have unseen replies, and a bounded set of their newest finished replies. Replies keep + * going after the chat is closed. */ export const activity = query({ args: {}, handler: async (ctx) => { const user = await getOptionalUser(ctx); - if (!user) return { working: false, unreadCount: 0, latest: null }; + if (!user) return { working: false, unreadCount: 0, latest: null, replies: [] }; const rows = await ctx.db .query('finaiConversations') .withIndex('by_user_updatedAt', (q) => q.eq('userId', user._id)) @@ -86,24 +96,22 @@ export const activity = query({ .take(50); const now = Date.now(); const unread = rows.filter((row) => row.unreadAt !== undefined); - const newest = unread.reduce | null>( - (best, row) => (!best || row.unreadAt! > best.unreadAt! ? row : best), - null, - ); + const replies = unread + .filter((row) => row.lastReplyId !== undefined) + .sort((a, b) => a.unreadAt! - b.unreadAt!) + .map((row) => ({ + conversationId: row._id, + replyId: row.lastReplyId!, + title: row.title ?? 'New chat', + preview: row.lastReplyFailed ? '' : (row.preview ?? ''), + failed: row.lastReplyFailed === true, + at: row.unreadAt!, + })); return { working: rows.some((row) => isWorking(row, now)), unreadCount: unread.length, - latest: - newest && newest.lastReplyId - ? { - conversationId: newest._id, - replyId: newest.lastReplyId, - title: newest.title ?? 'New chat', - preview: newest.lastReplyFailed ? '' : (newest.preview ?? ''), - failed: newest.lastReplyFailed === true, - at: newest.unreadAt!, - } - : null, + latest: replies.at(-1) ?? null, + replies, }; }, }); @@ -304,6 +312,10 @@ export const begin = internalMutation({ unreadAt: undefined, ...(isNew ? { title } : {}), }); + await ctx.scheduler.runAt(now + REPLY_STALE_MS, internal.ai.assistant.expireAbandoned, { + conversationId, + updatedAt: now, + }); const earlier = await ctx.db .query('finaiMessages') diff --git a/convex/ai/assistantTools.ts b/convex/ai/assistantTools.ts index 74850de5..c22c86e8 100644 --- a/convex/ai/assistantTools.ts +++ b/convex/ai/assistantTools.ts @@ -31,6 +31,35 @@ const toneForType = (type: string): Tone => /** Raw 100-row pages `search_transactions` may scan for matches. */ const SEARCH_MAX_PAGES = 10; +/** Search cursors retain a raw-page offset so matches beyond the requested limit aren't lost. */ +type SearchCursor = { finaiSearch: 1; pageCursor: string | null; offset: number }; + +function searchCursor(value: string | undefined): SearchCursor { + if (value) { + try { + const parsed: unknown = JSON.parse(value); + if ( + parsed && + typeof parsed === 'object' && + 'finaiSearch' in parsed && + parsed.finaiSearch === 1 && + 'pageCursor' in parsed && + (parsed.pageCursor === null || typeof parsed.pageCursor === 'string') && + 'offset' in parsed && + typeof parsed.offset === 'number' && + Number.isSafeInteger(parsed.offset) && + parsed.offset >= 0 + ) { + return parsed as SearchCursor; + } + } catch { + // Native Convex cursors aren't JSON search cursors. + } + return { finaiSearch: 1, pageCursor: value, offset: 0 }; + } + return { finaiSearch: 1, pageCursor: null, offset: 0 }; +} + function transactionItem( row: { id: string; @@ -218,25 +247,40 @@ export const assistantTools: FinaiTool[] = [ // Filters apply after pagination, so walk raw pages until enough rows match. type Row = FunctionReturnType['items'][number]; const items: Row[] = []; - let cursor: string | null = str(args, 'cursor', 2000) ?? null; + let { pageCursor, offset } = searchCursor(str(args, 'cursor', 10_000)); let isDone = false; for (let page = 0; page < SEARCH_MAX_PAGES && items.length < limit && !isDone; page++) { + const pageStartCursor = pageCursor; const result: FunctionReturnType = await ctx.run.runQuery( api.mcp.listTransactions, { ...filters, - paginationOpts: { numItems: 100, cursor }, + paginationOpts: { numItems: 100, cursor: pageCursor }, }, ); - items.push(...result.items); - cursor = result.nextCursor; + let consumed = Math.min(offset, result.items.length); + offset = 0; + while (consumed < result.items.length && items.length < limit) { + const item = result.items[consumed]; + if (item === undefined) break; + items.push(item); + consumed++; + } + + if (consumed < result.items.length) { + // Resume within this same raw page, re-reading but skipping rows already consumed. + pageCursor = pageStartCursor; + offset = consumed; + break; + } + pageCursor = result.nextCursor; isDone = result.isDone; } - // Stopped at the page budget with source left: hand back a cursor to continue from. + // A cursor includes the raw-page offset whenever more source rows remain. const result = { - items: items.slice(0, limit), - isDone: isDone && items.length <= limit, - cursor: !isDone && items.length < limit ? cursor : null, + items, + isDone, + cursor: !isDone ? JSON.stringify({ finaiSearch: 1, pageCursor, offset }) : null, }; return { data: { diff --git a/convex/ai/manageActions.ts b/convex/ai/manageActions.ts index bb84bec9..09598a33 100644 --- a/convex/ai/manageActions.ts +++ b/convex/ai/manageActions.ts @@ -72,18 +72,30 @@ export async function executeManageAction( const type = String(current.type); if (type !== 'expense' && type !== 'income' && type !== 'transfer') throw new Error('UNSUPPORTED_TYPE'); + const nextType = (text(payload, 'type') as 'expense' | 'income' | undefined) ?? type; + const transferAccountId = + payload.transferAccountId === null + ? undefined + : (current.transferAccountId as Id<'accounts'> | undefined); + const categoryId = + nextType !== type && nextType !== 'transfer' + ? (text(payload, 'categoryId') as Id<'categories'> | undefined) + : ((text(payload, 'categoryId') ?? (current.categoryId as string | undefined)) as + | Id<'categories'> + | undefined); + if (nextType !== type && nextType !== 'transfer' && !categoryId) + throw new Error('CATEGORY_REQUIRED_FOR_TYPE_CHANGE'); await ctx.runMutation(api.transactions.mutations.update, { transactionId: id as Id<'transactions'>, accountId: (text(payload, 'accountId') ?? current.accountId) as Id<'accounts'>, - type: (text(payload, 'type') as 'expense' | 'income' | undefined) ?? type, + type: nextType, amountMinor: big(payload, 'amountMinor') ?? asBig(current.amountMinor), currency: String(current.currency), - categoryId: (text(payload, 'categoryId') ?? (current.categoryId as string | undefined)) as - Id<'categories'> | undefined, + categoryId, title: text(payload, 'title') ?? String(current.title), merchant: text(payload, 'merchant') ?? (current.merchant as string | undefined), note: text(payload, 'note') ?? (current.note as string | undefined), - transferAccountId: current.transferAccountId as Id<'accounts'> | undefined, + transferAccountId, occurredAt: num(payload, 'occurredAt') ?? Number(current.occurredAt), hasTime: current.hasTime as boolean | undefined, clientMutationId, @@ -180,6 +192,7 @@ export async function executeManageAction( const id = await ctx.runMutation(api.accounts.mutations.create, { name: text(payload, 'name')!, type: type ?? 'bank', + customType: text(payload, 'customType'), currency: text(payload, 'currency')!, openingBalanceMinor: big(payload, 'openingBalanceMinor') ?? 0n, isIncludedInTotal: true, @@ -194,6 +207,11 @@ export async function executeManageAction( accountId: id as Id<'accounts'>, name: text(payload, 'name') ?? String(current.name), type: (text(payload, 'type') ?? current.type) as Doc<'accounts'>['type'], + customType: + text(payload, 'customType') ?? + ((text(payload, 'type') ?? current.type) === 'other' + ? (current.customType as string | undefined) + : undefined), currency: String(current.currency), openingBalanceMinor: big(payload, 'openingBalanceMinor') ?? asBig(current.openingBalanceMinor), @@ -217,7 +235,8 @@ export async function executeManageAction( case 'entity.delete': { const target = text(payload, 'kind'); const id = text(payload, 'id')!; - await record(ctx, userId, target ?? '', id); + const targetDoc = await record(ctx, userId, target ?? '', id); + if (target === 'category' && targetDoc.isSystem === true) throw new Error('SYSTEM_CATEGORY'); if (target === 'goal') await ctx.runMutation(api.goals.mutations.archive, { goalId: id as Id<'goals'>, @@ -243,9 +262,15 @@ export async function executeManageAction( return id; } case 'trash.purge': { + const kind = text(payload, 'kind')!; + const id = text(payload, 'id')!; + if (kind === 'category') { + const category = await record(ctx, userId, kind, id); + if (category.isSystem === true) throw new Error('SYSTEM_CATEGORY'); + } await ctx.runMutation(api.trash.purge, { - kind: text(payload, 'kind') as 'transaction', - id: text(payload, 'id')!, + kind: kind as 'transaction', + id, }); return text(payload, 'id'); } diff --git a/convex/ai/manageTools.ts b/convex/ai/manageTools.ts index 4e7da6ef..9bbe8223 100644 --- a/convex/ai/manageTools.ts +++ b/convex/ai/manageTools.ts @@ -56,25 +56,45 @@ export const manageTools: FinaiTool[] = [ { name: 'list_trash', description: - 'What is in the user’s Trash (deleted transactions, accounts, categories, budgets, goals, recurring), with ids and when each will be deleted for good.', + 'What is in the user’s Trash (deleted transactions, accounts, categories, budgets, goals, recurring), with ids and when each will be deleted for good. Use the returned cursor to read the next page.', parameters: s.object({ kind: s.enumOf('Only this kind (optional).', [...TRASH_KINDS]), + cursor: s.string('Cursor from the previous Trash page.'), }), progress: { stage: 'searching', label: 'Looking in Trash…' }, run: async (ctx, args) => { - const kind = oneOf(args, 'kind', TRASH_KINDS); - const result = await ctx.run.runQuery(api.trash.list, kind ? { kind } : {}); + const requestedKind = oneOf(args, 'kind', TRASH_KINDS); + const cursor = str(args, 'cursor', 20_000); + const separator = cursor?.indexOf(':') ?? -1; + const cursorPrefix = cursor?.slice(0, separator); + const cursorKind = + cursor === undefined || cursorPrefix === 'all' + ? undefined + : oneOf({ kind: cursorPrefix }, 'kind', TRASH_KINDS); + const pageCursor = cursor === undefined ? undefined : cursor.slice(separator + 1); + if ( + cursor !== undefined && + (separator < 1 || + (cursorPrefix !== 'all' && cursorKind === undefined) || + pageCursor === '' || + (requestedKind !== undefined && requestedKind !== cursorKind)) + ) + throw new ToolArgError('INVALID_CURSOR'); + const kind = requestedKind ?? cursorKind; + const result = await ctx.run.runQuery(api.trash.listPage, { kind, cursor: pageCursor }); + const items = result.items.map((item) => ({ + kind: item.kind, + id: item.id, + title: item.title, + detail: item.subtitle, + deletedOn: shortDate(item.deletedAt, ctx.timeZone), + deletedForGoodOn: item.purgeAt ? shortDate(item.purgeAt, ctx.timeZone) : 'never', + })); return { data: { retentionDays: result.retentionDays, - items: result.items.slice(0, 40).map((item) => ({ - kind: item.kind, - id: item.id, - title: item.title, - detail: item.subtitle, - deletedOn: shortDate(item.deletedAt, ctx.timeZone), - deletedForGoodOn: item.purgeAt ? shortDate(item.purgeAt, ctx.timeZone) : 'never', - })), + items, + nextCursor: result.cursor ? `${kind ?? 'all'}:${result.cursor}` : null, }, }; }, @@ -106,7 +126,13 @@ export const manageTools: FinaiTool[] = [ resource: 'recurringRules', paginationOpts: { numItems: 50, cursor: null }, }); - return { data: { items: page.items } }; + const items = []; + for (const item of page.items) { + const doc = await owned(ctx, 'recurring', String(item.id)); + if (doc.archivedAt !== undefined) continue; + items.push({ ...item, amountMinor: doc.amountMinor, currency: doc.currency }); + } + return { data: { items } }; }, }, { @@ -148,6 +174,13 @@ export const manageTools: FinaiTool[] = [ if (type) { payload.type = type; changes.push({ label: 'Kind', value: type }); + if (type !== doc.type) { + const categoryId = str(args, 'categoryId', 64); + if (!categoryId) throw new ToolArgError('CATEGORY_REQUIRED_FOR_TYPE_CHANGE'); + payload.categoryId = categoryId; + payload.transferAccountId = null; + changes.push({ label: 'Category', value: categoryId }); + } } for (const key of ['categoryId', 'accountId', 'merchant', 'note'] as const) { const value = str(args, key, key === 'note' ? 500 : 120); @@ -254,6 +287,8 @@ export const manageTools: FinaiTool[] = [ if (target === undefined) throw new ToolArgError('MISSING_AMOUNT'); const monthly = amountMinor(args, 'monthly', currency); const targetDate = date(args, 'targetDate'); + if (targetDate !== undefined && targetDate <= Date.now()) + throw new ToolArgError('TARGET_DATE_MUST_BE_FUTURE'); const name = requiredStr(args, 'name', 80); return propose(ctx, { kind: 'goal.create', @@ -308,6 +343,8 @@ export const manageTools: FinaiTool[] = [ lines.push({ label: 'Target', value: formatMinor(target, currency) }); } const targetDate = date(args, 'targetDate'); + if (targetDate !== undefined && targetDate <= Date.now()) + throw new ToolArgError('TARGET_DATE_MUST_BE_FUTURE'); if (targetDate) { payload.targetDate = targetDate; lines.push({ label: 'By', value: shortDate(targetDate, ctx.timeZone) }); @@ -428,6 +465,7 @@ export const manageTools: FinaiTool[] = [ 'loan', 'other', ]), + customType: s.string('Custom type when type is other.'), currency: s.string('ISO code. Default: the user’s default currency.'), openingBalance: s.amount('Opening balance (optional, default 0).'), }, @@ -440,13 +478,26 @@ export const manageTools: FinaiTool[] = [ const balance = amountMinor(args, 'openingBalance', currency) ?? 0n; const type = oneOf(args, 'type', ['cash', 'bank', 'card', 'wallet', 'loan', 'other'] as const) ?? 'bank'; + if (type === 'other' && !str(args, 'customType', 40)) + throw new ToolArgError('CUSTOM_TYPE_REQUIRED'); return propose(ctx, { kind: 'account.create', title: `New account: ${name}`, - payload: { name, type, currency, openingBalanceMinor: balance }, + payload: { + name, + type, + currency, + openingBalanceMinor: balance, + ...(type === 'other' && str(args, 'customType', 40) + ? { customType: str(args, 'customType', 40) } + : {}), + }, lines: [ { label: 'Type', value: type }, { label: 'Opening balance', value: formatMinor(balance, currency) }, + ...(type === 'other' && str(args, 'customType', 40) + ? [{ label: 'Custom type', value: str(args, 'customType', 40)! }] + : []), ], }); }, @@ -460,6 +511,7 @@ export const manageTools: FinaiTool[] = [ accountId: s.string('Account id.'), name: s.string('New name.'), type: s.enumOf('New type.', ['cash', 'bank', 'card', 'wallet', 'loan', 'other']), + customType: s.string('New custom type when type is other.'), openingBalance: s.amount('New opening balance.'), }, ['accountId'], @@ -487,6 +539,15 @@ export const manageTools: FinaiTool[] = [ payload.type = type; lines.push({ label: 'Type', value: type }); } + const customType = str(args, 'customType', 40); + const effectiveType = type ?? doc.type; + if (customType) { + if (effectiveType !== 'other') throw new ToolArgError('CUSTOM_TYPE_REQUIRES_OTHER'); + payload.customType = customType; + lines.push({ label: 'Custom type', value: customType }); + } else if (type === 'other' && doc.type !== 'other') { + throw new ToolArgError('CUSTOM_TYPE_REQUIRED'); + } const balance = amountMinor(args, 'openingBalance', currency); if (balance !== undefined) { payload.openingBalanceMinor = balance; @@ -524,13 +585,17 @@ export const manageTools: FinaiTool[] = [ if (amount === undefined) throw new ToolArgError('MISSING_AMOUNT'); const frequency = oneOf(args, 'frequency', ['daily', 'weekly', 'monthly', 'yearly'] as const); if (!frequency) throw new ToolArgError('MISSING_FREQUENCY'); - const nextOccurrence = date(args, 'firstDate') ?? Date.now() + DAY; + const firstDate = date(args, 'firstDate'); + if (firstDate !== undefined && firstDate <= Date.now()) + throw new ToolArgError('NEXT_DATE_MUST_BE_FUTURE'); + const nextOccurrence = firstDate ?? Date.now() + DAY; const accounts = await ctx.run.runQuery(api.accounts.queries.list, {}); const preferred = str(args, 'accountId', 64); - const account = - (preferred && accounts.find((row) => String(row.id) === preferred)) || - accounts.find((row) => row.currency === currency); - if (!account) throw new ToolArgError('NO_ACCOUNT_IN_CURRENCY'); + const account = preferred + ? accounts.find((row) => String(row.id) === preferred) + : accounts.find((row) => row.currency === currency); + if (!account) throw new ToolArgError(preferred ? 'ACCOUNT_NOT_FOUND' : 'NO_ACCOUNT_IN_CURRENCY'); + if (account.currency !== currency) throw new ToolArgError('ACCOUNT_CURRENCY_MISMATCH'); return propose(ctx, { kind: 'recurring.create', title: `New recurring: ${name}`, @@ -572,6 +637,8 @@ export const manageTools: FinaiTool[] = [ if (!kind) throw new ToolArgError('MISSING_KIND'); const id = requiredStr(args, 'id', 64); const doc = await owned(ctx, kind, id); + if (kind === 'category' && doc.isSystem === true) + throw new ToolArgError('SYSTEM_CATEGORY'); const withTransactions = kind === 'category' && (args.deleteTransactions === true || args.deleteTransactions === 'true'); @@ -611,6 +678,8 @@ export const manageTools: FinaiTool[] = [ if (!kind) throw new ToolArgError('MISSING_KIND'); const id = requiredStr(args, 'id', 64); const doc = await owned(ctx, kind, id); + if (kind === 'category' && doc.isSystem === true) + throw new ToolArgError('SYSTEM_CATEGORY'); const inTrash = kind === 'transaction' ? doc.deletedAt !== undefined : doc.archivedAt !== undefined; if (!inTrash) throw new ToolArgError('NOT_IN_TRASH'); diff --git a/convex/ai/prompts.ts b/convex/ai/prompts.ts index 7923e9ac..4420375b 100644 --- a/convex/ai/prompts.ts +++ b/convex/ai/prompts.ts @@ -6,9 +6,6 @@ Rules: - Amounts in tool results are exact: "...Minor" fields are integer minor units and "...Formatted" fields are ready to show. Quote the formatted values; do not do float maths. - Tools that change data ("propose_*") only prepare a confirmation card. After calling one, tell the user to review and press Confirm. Never say something was saved, paid or sent. - Cards appear under your reply automatically when tools return data, so keep the text short: lead with the answer in one or two sentences, then at most a few bullets. No tables. -- You can manage everything through tools: edit transactions; create or edit goals, categories, accounts and recurring payments; set category limits; delete things; and restore or permanently delete items in Trash. Never tell the user you can't do something a tool covers. -- Budgets are category limits: a budget is always a monthly limit on one category. Read them with list_category_limits and set, change or remove one with propose_category_limit (there are no separate budgets or overall budgets). -- Deleting a transaction (delete_transaction) happens right away and moves it to Trash; say it can be restored. Deleting goals, categories, accounts or recurring payments (propose_delete) and deleting anything for good (propose_purge) need the user's confirmation card. When deleting a category, ask whether its transactions should be kept or moved to Trash too. - Find ids with the list/search tools first; never guess an id. - The user can attach images, PDFs, spreadsheets and text files. Read them carefully (receipts, statements, bills) and answer from them. To add a spreadsheet's rows as transactions, call propose_import_transactions with the attachment id and the exact column names; never re-type rows yourself. For a single receipt or bill, use propose_transaction. - If a tool returns an error code, explain it plainly and suggest a next step. @@ -34,7 +31,12 @@ You are talking privately with ${input.name}. Today is ${input.today} (${input.t Their accounts: ${accounts} Their groups: -${groups}`; +${groups} + +Private management instructions: +- You can manage everything through tools: edit transactions; create or edit goals, categories, accounts and recurring payments; set category limits; delete things; and restore or permanently delete items in Trash. Never tell the user you can't do something a tool covers. +- Budgets are category limits: a budget is always a monthly limit on one category. Read them with list_category_limits and set, change or remove one with propose_category_limit (there are no separate budgets or overall budgets). +- Deleting a transaction (delete_transaction) happens right away and moves it to Trash; say it can be restored. Deleting goals, categories, accounts or recurring payments (propose_delete) and deleting anything for good (propose_purge) need the user's confirmation card. When deleting a category, ask whether its transactions should be kept or moved to Trash too.`; } export function chatSystemPrompt(input: { diff --git a/convex/trash.ts b/convex/trash.ts index 74bd5542..036d9ed6 100644 --- a/convex/trash.ts +++ b/convex/trash.ts @@ -176,6 +176,126 @@ export const list = query({ return { items: items.slice(0, LIST_LIMIT), retentionDays: days }; }, }); +/** + * A bounded page across Trash tables. Each source is paged independently, then merged; + * cursors advance only through rows included in the response. + */ +export const listPage = query({ + args: { kind: v.optional(kindValidator), cursor: v.optional(v.string()) }, + handler: async (ctx, { kind, cursor }) => { + const user = await getOptionalUser(ctx); + if (!user) + return { + items: [] as TrashItem[], + retentionDays: DEFAULT_TRASH_RETENTION_DAYS, + cursor: null, + }; + const days = await retentionDays(ctx, user._id); + let cursors: Partial> = {}; + if (cursor) { + try { + const parsed: unknown = JSON.parse(cursor); + if ( + parsed && + typeof parsed === 'object' && + TRASH_KINDS.every((each) => { + const value = (parsed as Record)[each]; + return value === undefined || value === null || typeof value === 'string'; + }) + ) + cursors = parsed as Partial>; + } catch { + cursors = {}; + } + } + + const kinds = kind ? [kind] : TRASH_KINDS; + const pages = await Promise.all( + kinds.map(async (each) => { + const initialCursor = cursors[each] ?? null; + const paginationOpts = { numItems: 40, cursor: initialCursor }; + const page = + each === 'transaction' + ? await ctx.db + .query('transactions') + .withIndex('by_owner_deletedAt', (q) => + q.eq('ownerId', user._id).gt('deletedAt', 0), + ) + .order('desc') + .paginate(paginationOpts) + : await ctx.db + .query(TABLE[each] as 'accounts' | 'categories' | 'budgets' | 'goals' | 'recurringRules') + .withIndex('by_owner_archivedAt', (q) => + q.eq('ownerId', user._id).gt('archivedAt', 0), + ) + .order('desc') + .paginate(paginationOpts); + const entries = page.page.flatMap((row, index) => { + const doc = row as unknown as Record; + if (each === 'transaction' && doc.groupId !== undefined) return []; + const deletedAt = deletedAtOf(each, doc); + return [{ + item: { + kind: each, + id: String(row._id), + ...describe(each, doc), + deletedAt, + purgeAt: days > 0 ? deletedAt + days * DAY : null, + } satisfies TrashItem, + index, + }]; + }); + return { kind: each, page, entries, initialCursor }; + }), + ); + + const entries = pages + .flatMap(({ entries }) => entries) + .sort((a, b) => b.item.deletedAt - a.item.deletedAt); + const selected = entries.slice(0, 40); + const items = selected.map(({ item }) => item); + const nextCursors: Partial> = {}; + await Promise.all( + pages.map(async ({ kind: each, page, entries: sourceEntries, initialCursor }) => { + const selectedEntries = selected.filter((entry) => entry.item.kind === each); + const consumed = selectedEntries.length + ? selectedEntries[selectedEntries.length - 1]!.index + 1 + : sourceEntries.length === 0 + ? page.page.length + : 0; + if (consumed === page.page.length) { + nextCursors[each] = page.continueCursor; + } else if (consumed === 0) { + nextCursors[each] = initialCursor; + } else { + const advanced = + each === 'transaction' + ? await ctx.db + .query('transactions') + .withIndex('by_owner_deletedAt', (q) => + q.eq('ownerId', user._id).gt('deletedAt', 0), + ) + .order('desc') + .paginate({ numItems: consumed, cursor: initialCursor }) + : await ctx.db + .query(TABLE[each] as 'accounts' | 'categories' | 'budgets' | 'goals' | 'recurringRules') + .withIndex('by_owner_archivedAt', (q) => + q.eq('ownerId', user._id).gt('archivedAt', 0), + ) + .order('desc') + .paginate({ numItems: consumed, cursor: initialCursor }); + nextCursors[each] = advanced.continueCursor; + } + }), + ); + const more = pages.some(({ page }) => !page.isDone) || entries.length > items.length; + return { + items, + retentionDays: days, + cursor: more ? JSON.stringify(nextCursors) : null, + }; + }, +}); export const setRetention = mutation({ args: { days: v.number() }, diff --git a/packages/ui/src/ai/streamedText.ts b/packages/ui/src/ai/streamedText.ts index c0c09039..d34e6da4 100644 --- a/packages/ui/src/ai/streamedText.ts +++ b/packages/ui/src/ai/streamedText.ts @@ -64,6 +64,12 @@ export function useStreamedText(text: string, streaming: boolean): string { React.useEffect(() => { if (!animate.current) return; + if (!streaming) { + // Completion can trigger the parent’s final scroll before another animation frame runs. + // Render the full reply immediately, then sync state for a possible subsequent stream. + setShown(target); + return; + } if (shownRef.current >= target) return; const rate = revealRate(target - shownRef.current); let frame = 0; @@ -79,8 +85,10 @@ export function useStreamedText(text: string, streaming: boolean): string { }; frame = requestAnimationFrame(tick); return () => cancelAnimationFrame(frame); - }, [target]); + }, [target, streaming]); - if (!animate.current || shown >= target) return text; + // Completion must render the full reply in this render, before the parent's final auto-scroll. + // Keep `shown` in sync afterward in case this mounted renderer is reused for another stream. + if (!animate.current || !streaming || shown >= target) return text; return balancePartialMarkdown(text.slice(0, shown)); } diff --git a/tests/convex/ai-stream-writer.test.ts b/tests/convex/ai-stream-writer.test.ts index eb821abf..88658e57 100644 --- a/tests/convex/ai-stream-writer.test.ts +++ b/tests/convex/ai-stream-writer.test.ts @@ -1,4 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { convexTest } from 'convex-test'; +import { api, internal } from '../../convex/_generated/api'; +import schema from '../../convex/schema'; import { createStreamWriter } from '../../convex/ai/streamWriter'; beforeEach(() => { @@ -91,3 +94,30 @@ describe('createStreamWriter', () => { expect(write).toHaveBeenCalledTimes(1); }); }); + +describe('FinAI stale activity', () => { + it('expires abandoned work on schedule so activity subscriptions update', async () => { + const t = convexTest(schema, import.meta.glob('../../convex/**/*.ts')); + const userId = await t.run(async (ctx) => + ctx.db.insert('users', { + email: 'stale-activity@example.com', + displayName: 'Stale Activity', + emailVerificationTime: Date.now(), + defaultCurrency: 'USD', + }), + ); + const owner = t.withIdentity({ subject: `${userId}|session` }); + + const { conversationId } = await owner.mutation(internal.ai.assistant.begin, { + text: 'A reply that will be abandoned', + }); + expect((await owner.query(api.ai.assistant.activity, {})).working).toBe(true); + + await t.finishAllScheduledFunctions(() => vi.advanceTimersByTime(6 * 60_000)); + + expect((await owner.query(api.ai.assistant.activity, {})).working).toBe(false); + expect((await owner.query(api.ai.assistant.conversations, {})).find((row) => row.id === conversationId)) + .toMatchObject({ working: false }); + }); +}); + diff --git a/tests/convex/finai-manage-mcp-access.test.ts b/tests/convex/finai-manage-mcp-access.test.ts index a9a5e54e..001e5c2c 100644 --- a/tests/convex/finai-manage-mcp-access.test.ts +++ b/tests/convex/finai-manage-mcp-access.test.ts @@ -1,3 +1,6 @@ +import { manageTools } from '../../convex/ai/manageTools'; +import { assistantSystemPrompt, chatSystemPrompt } from '../../convex/ai/prompts'; + import { describe, expect, it } from 'vitest'; import { convexTest } from 'convex-test'; import { api } from '../../convex/_generated/api'; @@ -93,6 +96,127 @@ async function setup() { return { t, me, userId, ids, confirm }; } +async function runManageTool(name: string, args: Record, ctx: unknown) { + const tool = manageTools.find((item) => item.name === name); + if (!tool) throw new Error(`Missing tool: ${name}`); + return tool.run(ctx as never, args); +} + +function resultItems(result: { data: unknown }): unknown[] { + if (result.data && typeof result.data === 'object' && 'items' in result.data) { + const items = result.data.items; + if (Array.isArray(items)) return items; + } + throw new Error('Expected tool result items'); +} + +describe('FinAI management tools', () => { + const context = (runQuery: (query: unknown, args: Record) => Promise) => + ({ + run: { runQuery, runMutation: async () => 'action-id' }, + userId: 'user-id', + scope: { type: 'assistant', id: 'conversation' }, + messageId: 'message', + defaultCurrency: 'INR', + timeZone: 'UTC', + }) as unknown; + + it('paginates Trash results instead of truncating them at 40', async () => { + const items = Array.from({ length: 45 }, (_, index) => ({ + kind: 'transaction' as const, + id: `id-${index}`, + title: `Item ${index}`, + subtitle: 'detail', + deletedAt: 1, + purgeAt: 2, + })); + const ctx = context(async (_query, args) => + args.cursor + ? { items: items.slice(40), retentionDays: 30, cursor: null } + : { items: items.slice(0, 40), retentionDays: 30, cursor: 'cursor-2' }, + ); + const first = await runManageTool('list_trash', {}, ctx); + expect(resultItems(first)).toHaveLength(40); + expect(first.data).toMatchObject({ nextCursor: 'all:cursor-2' }); + const second = await runManageTool('list_trash', { cursor: 'all:cursor-2' }, ctx); + expect(resultItems(second)).toHaveLength(5); + expect(second.data).toMatchObject({ nextCursor: null }); + }); + + it('omits archived recurring rules and includes active amounts and currencies', async () => { + const ctx = context(async (_query, args) => { + if (args.resource === 'recurringRules') + return { + items: [ + { id: 'active', name: 'Rent', frequency: 'monthly', nextOccurrence: 1 }, + { id: 'archived', name: 'Old', frequency: 'monthly', nextOccurrence: 1 }, + ], + }; + return args.id === 'active' + ? { amountMinor: 12_500n, currency: 'INR' } + : { amountMinor: 4_000n, currency: 'USD', archivedAt: 1 }; + }); + const result = await runManageTool('list_recurring', {}, ctx); + expect(resultItems(result)).toMatchObject([ + { id: 'active', amountMinor: 12_500n, currency: 'INR' }, + ]); + }); + + it('rejects a preferred account whose currency conflicts with recurring currency', async () => { + const ctx = context(async () => [{ id: 'account', name: 'Dollar account', currency: 'USD' }]); + await expect( + runManageTool( + 'propose_recurring', + { + name: 'Rent', + amount: '10', + frequency: 'monthly', + firstDate: '2030-01-01', + accountId: 'account', + currency: 'INR', + }, + ctx, + ), + ).rejects.toThrow('ACCOUNT_CURRENCY_MISMATCH'); + }); + + it('rejects past goal target dates before creating a confirmation card', async () => { + const ctx = context(async () => []); + await expect( + runManageTool( + 'propose_goal', + { name: 'Goal', target: '100', targetDate: '2000-01-01' }, + ctx, + ), + ).rejects.toThrow('TARGET_DATE_MUST_BE_FUTURE'); + }); +}); + +describe('FinAI prompt scope', () => { + it('keeps management instructions out of shared chat prompts', () => { + const chat = chatSystemPrompt({ + scope: 'group', + title: 'Friends', + today: '2026-11-27', + requesterName: 'Owner', + participants: [], + groups: [], + }); + const assistant = assistantSystemPrompt({ + name: 'Owner', + today: '2026-11-27', + timezone: 'UTC', + defaultCurrency: 'INR', + accounts: [], + groups: [], + }); + expect(chat).not.toContain('Private management instructions'); + expect(chat).not.toContain('propose_category_limit'); + expect(assistant).toContain('Private management instructions'); + expect(assistant).toContain('propose_category_limit'); + }); +}); + describe('FinAI management actions', () => { it('creates and edits a goal, keeping fields that were not mentioned', async () => { const { t, confirm } = await setup(); @@ -164,6 +288,105 @@ describe('FinAI management actions', () => { expect((await t.run((ctx) => ctx.db.get(strangerAccount)))?.archivedAt).toBeUndefined(); }); + it('refuses deletion of system categories even through a confirmed action', async () => { + const { t, userId, confirm } = await setup(); + const categoryId = await t.run((ctx) => + ctx.db.insert('categories', { + ownerId: userId, + name: 'System', + kind: 'expense', + isSystem: true, + sortOrder: 0, + createdAt: 1, + updatedAt: 1, + }), + ); + const result = await confirm('entity.delete', { + kind: 'category', + id: String(categoryId), + }); + expect(result.status).toBe('failed'); + expect((await t.run((ctx) => ctx.db.get(categoryId)))?.archivedAt).toBeUndefined(); + }); + + it('persists the custom type for created and retyped other accounts', async () => { + const { t, ids, confirm } = await setup(); + const updated = await confirm('account.update', { + accountId: String(ids.accountId), + type: 'other', + customType: 'Brokerage', + }); + expect(updated.status).toBe('done'); + expect(await t.run((ctx) => ctx.db.get(ids.accountId))).toMatchObject({ + type: 'other', + customType: 'Brokerage', + }); + const relabeled = await confirm('account.update', { + accountId: String(ids.accountId), + customType: 'Investment account', + }); + expect(relabeled.status).toBe('done'); + expect(await t.run((ctx) => ctx.db.get(ids.accountId))).toMatchObject({ + type: 'other', + customType: 'Investment account', + }); + const created = await confirm('account.create', { + name: 'Investment', + type: 'other', + customType: 'Brokerage', + currency: 'INR', + openingBalanceMinor: 0n, + }); + expect(created.status).toBe('done'); + expect(await t.run((ctx) => ctx.db.get(created.resultId as never))).toMatchObject({ + type: 'other', + customType: 'Brokerage', + }); + }); + + it('clears transfer fields and requires a category when changing transaction type', async () => { + const { t, userId, ids, confirm } = await setup(); + const transferId = await t.run((ctx) => + ctx.db.insert('transactions', { + ownerId: userId, + accountId: ids.accountId, + transferAccountId: String(ids.accountId), + type: 'transfer', + amountMinor: 500n, + currency: 'INR', + title: 'Transfer', + occurredAt: Date.now(), + status: 'posted', + createdAt: Date.now(), + updatedAt: Date.now(), + }), + ); + expect( + ( + await confirm('transaction.update', { + transactionId: String(transferId), + type: 'expense', + }) + ).status, + ).toBe('failed'); + expect( + ( + await confirm('transaction.update', { + transactionId: String(transferId), + type: 'expense', + categoryId: String(ids.categoryId), + transferAccountId: null, + }) + ).status, + ).toBe('done'); + const updated = await t.run((ctx) => ctx.db.get(transferId)); + expect(updated).toMatchObject({ + type: 'expense', + categoryId: String(ids.categoryId), + }); + expect(updated?.transferAccountId).toBeUndefined(); + }); + it('delete and restore tools follow the "prepare changes" setting', () => { const off = resolveFinaiSettings({ allowActions: false }); expect(finaiToolAllowed(off, 'delete_transaction')).toBe(false); diff --git a/tests/convex/finai-search.test.ts b/tests/convex/finai-search.test.ts new file mode 100644 index 00000000..0f124488 --- /dev/null +++ b/tests/convex/finai-search.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it, vi } from 'vitest'; +import { assistantTools } from '../../convex/ai/assistantTools'; + +const tool = assistantTools.find((candidate) => candidate.name === 'search_transactions')!; + +describe('FinAI transaction search pagination', () => { + it('returns every match across raw pages when each page exceeds the result limit', async () => { + const rows = Array.from({ length: 200 }, (_, index) => ({ + id: `transaction-${index}`, + title: `Match ${index}`, + type: 'expense', + amountMinor: 100n, + currency: 'USD', + occurredAt: Date.UTC(2025, 0, 1) - index, + })); + const runQuery = vi.fn(async (_ref: unknown, args: unknown) => { + const { paginationOpts } = args as { + paginationOpts: { cursor: string | null }; + }; + const page = paginationOpts.cursor === 'page-2' ? 1 : 0; + return { + items: rows.slice(page * 100, (page + 1) * 100), + nextCursor: page === 0 ? 'page-2' : 'page-3', + isDone: page === 1, + }; + }); + const ctx = { + run: { runQuery }, + defaultCurrency: 'USD', + timeZone: 'UTC', + } as never; + + const received: string[] = []; + let cursor: string | undefined; + let more = true; + while (more) { + const result = await tool.run(ctx, { query: 'Match', limit: 20, cursor }); + const data = result.data as { + items: { id: string }[]; + more: boolean; + cursor?: string; + }; + received.push(...data.items.map((item) => item.id)); + more = data.more; + cursor = data.cursor; + if (more) expect(cursor).toBeTruthy(); + } + + expect(received).toEqual(rows.map((row) => row.id)); + expect(new Set(received).size).toBe(200); + expect(runQuery).toHaveBeenCalledTimes(10); + }); +}); diff --git a/tests/convex/finai.test.ts b/tests/convex/finai.test.ts index 24820349..1531dd00 100644 --- a/tests/convex/finai.test.ts +++ b/tests/convex/finai.test.ts @@ -180,6 +180,7 @@ describe('FinAI assistant', () => { working: false, unreadCount: 0, latest: null, + replies: [], }); // While a reply is being written the conversation is working. const conversationId = await owner.mutation(api.ai.assistant.createConversation, {}); @@ -198,6 +199,7 @@ describe('FinAI assistant', () => { preview: 'Your spending is steady.', failed: false, }, + replies: [{ conversationId: other.conversationId, replyId: other.replyId }], }); const listed = await owner.query(api.ai.assistant.conversations, {}); expect(listed.find((row) => row.id === other.conversationId)).toMatchObject({ @@ -206,13 +208,22 @@ describe('FinAI assistant', () => { }); expect(listed.find((row) => row.id === conversationId)).toMatchObject({ working: true }); + mockGemini([{ text: 'Here is another update.' }]); + const additional = await owner.action(api.ai.assistant.send, { text: 'and another?' }); + const withBoth = await owner.query(api.ai.assistant.activity, {}); + expect(withBoth.replies.map((reply) => reply.replyId)).toEqual( + expect.arrayContaining([other.replyId, additional.replyId]), + ); + // Someone else can't clear it; opening the chat does. await outsider.mutation(api.ai.assistant.markRead, { conversationId: other.conversationId }); - expect((await owner.query(api.ai.assistant.activity, {})).unreadCount).toBe(1); + expect((await owner.query(api.ai.assistant.activity, {})).unreadCount).toBe(2); await owner.mutation(api.ai.assistant.markRead, { conversationId: other.conversationId }); + await owner.mutation(api.ai.assistant.markRead, { conversationId: additional.conversationId }); expect(await owner.query(api.ai.assistant.activity, {})).toMatchObject({ unreadCount: 0, latest: null, + replies: [], }); // A failed reply is unread too, and says so. diff --git a/tests/convex/trash.test.ts b/tests/convex/trash.test.ts index 841a5f62..846cb89c 100644 --- a/tests/convex/trash.test.ts +++ b/tests/convex/trash.test.ts @@ -3,6 +3,7 @@ import { convexTest } from 'convex-test'; import { api, internal } from '../../convex/_generated/api'; import schema from '../../convex/schema'; import { defaultNotificationPreferences } from '../../convex/notifications/domain'; +import { manageTools } from '../../convex/ai/manageTools'; const modules = import.meta.glob('../../convex/**/*.ts'); const DAY = 86_400_000; @@ -94,6 +95,60 @@ describe('Trash', () => { expect((await owner.as.query(api.trash.list, {})).items).toHaveLength(0); }); + it('continues list_trash through more than 200 records without losing older items', async () => { + const { t, owner, ids } = await setup(); + const count = 225; + const base = Date.UTC(2025, 0, 1); + await t.run(async (ctx) => { + for (let index = 0; index < count; index++) { + await ctx.db.insert('transactions', { + ownerId: owner.userId, + accountId: ids.accountId, + type: 'expense', + amountMinor: 100n, + currency: 'INR', + categoryId: String(ids.categoryId), + title: `Trash ${index}`, + occurredAt: base + index, + status: 'posted', + createdAt: base + index, + updatedAt: base + index, + deletedAt: base + index, + }); + } + }); + + expect((await owner.as.query(api.trash.list, {})).items).toHaveLength(200); + const tool = manageTools.find((candidate) => candidate.name === 'list_trash')!; + const ctx = { + run: { + runQuery: (ref: never, args: never) => owner.as.query(ref, args), + } as never, + userId: owner.userId, + scope: { type: 'assistant' as const, id: 'conversation' }, + messageId: 'message-1', + defaultCurrency: 'INR', + timeZone: 'UTC', + }; + const seen = new Set(); + let cursor: string | undefined; + let nextCursor: string | null = 'start'; + let pages = 0; + while (nextCursor && pages < 10) { + pages++; + const result = await tool.run(ctx, cursor ? { cursor } : {}); + const data = result.data as { + items: { id: string }[]; + nextCursor: string | null; + }; + for (const item of data.items) seen.add(item.id); + nextCursor = data.nextCursor; + cursor = nextCursor ?? undefined; + } + expect(nextCursor).toBeNull(); + expect(seen.size).toBe(count); + }); + it('deletes a category with its transactions and restores them together', async () => { const { t, owner, ids } = await setup(); await owner.as.mutation(api.categories.mutations.archive, { diff --git a/tests/web/finai-activity.test.ts b/tests/web/finai-activity.test.ts new file mode 100644 index 00000000..c81f75a4 --- /dev/null +++ b/tests/web/finai-activity.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest'; +import type { FinaiLatestReply } from '../../packages/ui/src/ai/finai'; +import { + collectUnseenReplies, + type FinaiActivityTracker, +} from '../../apps/web/lib/finai/activityTracker'; + +const reply = (replyId: string): FinaiLatestReply => ({ + conversationId: 'conversation', + replyId, + title: replyId, + preview: '', + failed: false, + at: 1, +}); + +describe('FinAI activity tracking', () => { + it('preserves seen replies across temporary query unavailability', () => { + const tracker: FinaiActivityTracker = { userId: 'alice', seenReplyIds: null }; + const existing = reply('existing'); + const completedDuringDisconnect = reply('completed-during-disconnect'); + + expect(collectUnseenReplies(tracker, 'alice', { replies: [existing] })).toEqual([]); + expect(collectUnseenReplies(tracker, 'alice', undefined)).toEqual([]); + expect( + collectUnseenReplies(tracker, 'alice', { + replies: [existing, completedDuringDisconnect], + }), + ).toEqual([completedDuringDisconnect]); + }); + + it('seeds a fresh baseline when the signed-in user changes', () => { + const tracker: FinaiActivityTracker = { userId: 'alice', seenReplyIds: null }; + expect(collectUnseenReplies(tracker, 'alice', { replies: [reply('alice-reply')] })).toEqual([]); + + const existingForBob = reply('bob-existing'); + expect(collectUnseenReplies(tracker, 'bob', { replies: [existingForBob] })).toEqual([]); + expect( + collectUnseenReplies(tracker, 'bob', { + replies: [existingForBob, reply('bob-new')], + }).map(({ replyId }) => replyId), + ).toEqual(['bob-new']); + }); +});