diff --git a/apps/mobile/hooks/useFinaiAssistant.ts b/apps/mobile/hooks/useFinaiAssistant.ts index 8b222369..c1bcb2eb 100644 --- a/apps/mobile/hooks/useFinaiAssistant.ts +++ b/apps/mobile/hooks/useFinaiAssistant.ts @@ -44,7 +44,7 @@ export function useFinaiAssistant(enabled: boolean, initialId: string | null = n const discard = useMutation(api.ai.attachments.discard); const composer = useComposerFiles<{ uri: string; mimeType?: string }>({ upload: async (file: PickedFile<{ uri: string; mimeType?: string }>) => { - const { uploadUrl: url } = await uploadUrl({}); + const { uploadUrl: url, ticket } = await uploadUrl({}); const blob = await (await fetch(file.source.uri)).blob(); const response = await fetch(url, { method: 'POST', @@ -55,7 +55,7 @@ export function useFinaiAssistant(enabled: boolean, initialId: string | null = n }); if (!response.ok) return { error: 'UPLOAD_FAILED' }; const { storageId } = (await response.json()) as { storageId: string }; - const result = await register({ storageId: storageId as Id<'_storage'>, name: file.name }); + const result = await register({ ticket, storageId: storageId as Id<'_storage'>, name: file.name }); return 'attachment' in result && result.attachment ? { id: String(result.attachment.id) } : { error: 'error' in result ? String(result.error) : 'UPLOAD_FAILED' }; diff --git a/apps/web/lib/finai/useFinaiAssistant.ts b/apps/web/lib/finai/useFinaiAssistant.ts index eb8a7162..523a3e88 100644 --- a/apps/web/lib/finai/useFinaiAssistant.ts +++ b/apps/web/lib/finai/useFinaiAssistant.ts @@ -46,7 +46,7 @@ export function useFinaiAssistant(enabled: boolean, initialId: string | null = n const discard = useMutation(api.ai.attachments.discard); const composer = useComposerFiles({ upload: async (file: PickedFile) => { - const { uploadUrl: url } = await uploadUrl({}); + const { uploadUrl: url, ticket } = await uploadUrl({}); const blob = file.source; const response = await fetch(url, { method: 'POST', @@ -55,7 +55,7 @@ export function useFinaiAssistant(enabled: boolean, initialId: string | null = n }); if (!response.ok) return { error: 'UPLOAD_FAILED' }; const { storageId } = (await response.json()) as { storageId: string }; - const result = await register({ storageId: storageId as Id<'_storage'>, name: file.name }); + const result = await register({ ticket, storageId: storageId as Id<'_storage'>, name: file.name }); return 'attachment' in result && result.attachment ? { id: String(result.attachment.id) } : { error: 'error' in result ? String(result.error) : 'UPLOAD_FAILED' }; diff --git a/convex/ai/actions.ts b/convex/ai/actions.ts index 5c06bf9e..36d0dd93 100644 --- a/convex/ai/actions.ts +++ b/convex/ai/actions.ts @@ -306,7 +306,11 @@ export const confirm = action({ } catch (error) { const errorCode = toolErrorCode(error); console.warn('[ai] FinAI action failed', claimed.kind, errorCode); - await ctx.runMutation(internal.ai.actions.finish, { actionId, status: 'failed', errorCode }); + await ctx.runMutation(internal.ai.actions.finish, { + actionId, + status: claimed.kind === 'transaction.import' ? 'running' : 'failed', + errorCode, + }); return { status: 'failed', errorCode }; } }, diff --git a/convex/ai/attachmentContent.ts b/convex/ai/attachmentContent.ts index ba425968..a0fa1a5a 100644 --- a/convex/ai/attachmentContent.ts +++ b/convex/ai/attachmentContent.ts @@ -23,7 +23,10 @@ export type ModelAttachment = { const isPdf = (bytes: Uint8Array) => bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46; // %PDF -const isZip = (bytes: Uint8Array) => bytes[0] === 0x50 && bytes[1] === 0x4b; // PK +const isZip = (bytes: Uint8Array) => + (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x03 && bytes[3] === 0x04) || + (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x05 && bytes[3] === 0x06) || + (bytes[0] === 0x50 && bytes[1] === 0x4b && bytes[2] === 0x07 && bytes[3] === 0x08); /** Reads a spreadsheet attachment's sheets (xlsx by bytes; otherwise CSV/TSV text). */ export function readSheets(bytes: Uint8Array, name: string): Sheet[] { diff --git a/convex/ai/attachments.ts b/convex/ai/attachments.ts index 89f6a7d8..ff509b38 100644 --- a/convex/ai/attachments.ts +++ b/convex/ai/attachments.ts @@ -94,8 +94,21 @@ export const generateUploadUrl = mutation({ const settings = await loadFinaiSettings(ctx, user._id); if (!settings.enabled) throw aiError('AI_DISABLED'); if (!settings.allowAttachments) throw new Error('ATTACHMENTS_DISABLED'); + const now = Date.now(); + const ticket = crypto.randomUUID(); + const uploadId = await ctx.db.insert('finaiAttachmentUploads', { + ticket, + userId: user._id, + createdAt: now, + }); + await ctx.scheduler.runAt( + now + finaiAttachmentLimits.registerWindowMs + 60_000, + internal.ai.attachments.expireUpload, + { uploadId }, + ); return { uploadUrl: await ctx.storage.generateUploadUrl(), + ticket, maxBytes: finaiAttachmentLimits.maxBytes, perMessage: finaiAttachmentLimits.perMessage, extensions: Object.keys(BY_EXTENSION), @@ -103,24 +116,29 @@ export const generateUploadUrl = mutation({ }, }); -/** - * Records an uploaded file for the signed-in user. Files that are too big, empty or of an - * unsupported type are deleted and reported as `{ error }` (returned, not thrown, so the - * deletion commits). Uploads that are too old or already used elsewhere are refused untouched. - */ +/** Registers a ticket's uploaded file or deletes a known invalid object. */ export const register = mutation({ - args: { storageId: v.id('_storage'), name: v.string() }, - handler: async (ctx, { storageId, name }) => { + args: { ticket: v.string(), storageId: v.id('_storage'), name: v.string() }, + handler: async (ctx, { ticket, storageId, name }) => { const user = await requireUser(ctx); if (!user || user.deletedAt !== undefined) throw new Error('AUTH_REQUIRED'); + const upload = await ctx.db + .query('finaiAttachmentUploads') + .withIndex('by_ticket', (q) => q.eq('ticket', ticket)) + .unique(); const file = await ctx.db.system.get('_storage', storageId); - if (!file) throw new Error('UPLOAD_NOT_FOUND'); const now = Date.now(); if ( - now - file._creationTime > finaiAttachmentLimits.registerWindowMs || + !upload || + upload.userId !== user._id || + upload.storageId !== undefined || + now - upload.createdAt > finaiAttachmentLimits.registerWindowMs || + !file || + file._creationTime < upload.createdAt - 1000 || (await storageInUse(ctx, storageId)) ) throw new Error('INVALID_UPLOAD'); + await ctx.db.patch(upload._id, { storageId }); const fileName = cleanFileName(name); const type = attachmentKind(fileName, file.contentType); const error = @@ -133,6 +151,7 @@ export const register = mutation({ : null; if (error || !type) { await ctx.storage.delete(storageId); + await ctx.db.delete(upload._id); return { error: error ?? 'UNSUPPORTED_FILE' } as const; } const id = await ctx.db.insert('finaiAttachments', { @@ -145,10 +164,28 @@ export const register = mutation({ createdAt: now, expiresAt: now + finaiAttachmentLimits.pendingTtlMs, }); + await ctx.db.delete(upload._id); return { attachment: await presentAttachment(ctx, (await ctx.db.get(id))!) } as const; }, }); +/** Deletes an expired ticket and its known uploaded object if it is not in use. */ +export const expireUpload = internalMutation({ + args: { uploadId: v.id('finaiAttachmentUploads') }, + handler: async (ctx, { uploadId }) => { + const upload = await ctx.db.get(uploadId); + if (!upload) return; + if ( + upload.storageId && + !(await storageInUse(ctx, upload.storageId)) && + (await ctx.db.system.get('_storage', upload.storageId)) + ) + await ctx.storage.delete(upload.storageId); + await ctx.db.delete(uploadId); + }, +}); + + async function deleteFile(ctx: MutationCtx, row: Doc<'finaiAttachments'>) { if (row.storageId && (await ctx.db.system.get('_storage', row.storageId))) await ctx.storage.delete(row.storageId); diff --git a/convex/ai/importTools.ts b/convex/ai/importTools.ts index 85cc08a3..3b599bb9 100644 --- a/convex/ai/importTools.ts +++ b/convex/ai/importTools.ts @@ -80,6 +80,14 @@ export const importTools: FinaiTool[] = [ ? sheets.find((entry) => entry.name.toLowerCase() === wanted.toLowerCase()) : sheets[0]; if (!sheet) throw new ToolArgError('SHEET_NOT_FOUND'); + if (sheet.truncated) + return { + data: { + error: 'SPREADSHEET_TRUNCATED', + parsedRows: sheet.rows.length, + note: 'This sheet reached a parser limit, so its total row count is unknown. No import was proposed.', + }, + }; const account = await chooseAccount(ctx.run, str(args, 'accountId', 64)); const mapping: ImportMapping = { diff --git a/convex/ai/providers.ts b/convex/ai/providers.ts index 13aac5f0..a307049a 100644 --- a/convex/ai/providers.ts +++ b/convex/ai/providers.ts @@ -363,6 +363,20 @@ async function openAiChat( return finish(text, functionCalls, finishReason === 'length', usage, config.model, finishReason); } +function assertAnthropicImageTypes(contents: GeminiContent[]) { + for (const content of contents) { + for (const part of content.parts) { + const mimeType = part.inlineData?.mimeType.toLowerCase(); + if (mimeType === 'image/heic' || mimeType === 'image/heif') { + throw aiError( + 'AI_REQUEST_REJECTED', + 'Anthropic does not support HEIC/HEIF images. Convert the image to JPEG, PNG, or WebP and try again.', + ); + } + } + } +} + /** Anthropic Messages API (alternating roles, tool_use / tool_result blocks). */ export function anthropicMessages(contents: GeminiContent[]) { const messages: { role: 'user' | 'assistant'; content: Record[] }[] = []; @@ -409,6 +423,7 @@ async function anthropicChat( config: ProviderConfig, options: ChatStreamOptions, ): Promise { + assertAnthropicImageTypes(options.contents); const defaults = aiGeneration[options.role]; const body = { model: config.model, diff --git a/convex/ai/receipts.ts b/convex/ai/receipts.ts index fe3e28a7..e6fa0774 100644 --- a/convex/ai/receipts.ts +++ b/convex/ai/receipts.ts @@ -88,11 +88,31 @@ export const generateUploadUrl = mutation({ }); /** - * Files already used by chat messages or FinAI attachments; those are never scratch uploads - * (neither a receipt nor an attachment may claim or delete them). + * Storage IDs referenced by any live app record are not scratch uploads and must not be deleted. */ -export async function storageInUse(ctx: MutationCtx, storageId: Id<'_storage'>): Promise { - const [directMessage, groupMessage, attachment] = await Promise.all([ +const ORPHAN_STORAGE_GRACE_MS = 24 * 60 * 60 * 1000; +const ORPHAN_STORAGE_PAGE_SIZE = 64; + +/** Returns whether any live app record still owns this stored file. */ +export async function storageInUse( + ctx: MutationCtx, + storageId: Id<'_storage'>, + ignoredReceiptUploadId?: Id<'aiReceiptUploads'>, +): Promise { + const [ + receipt, + directMessage, + groupMessage, + attachment, + attachmentUpload, + receiptUploads, + avatar, + user, + ] = await Promise.all([ + ctx.db + .query('receipts') + .withIndex('by_storage', (q) => q.eq('storageId', storageId)) + .first(), ctx.db .query('directMessages') .withIndex('by_storage', (q) => q.eq('storageId', storageId)) @@ -105,10 +125,61 @@ export async function storageInUse(ctx: MutationCtx, storageId: Id<'_storage'>): .query('finaiAttachments') .withIndex('by_storage', (q) => q.eq('storageId', storageId)) .first(), + ctx.db + .query('finaiAttachmentUploads') + .withIndex('by_storage', (q) => q.eq('storageId', storageId)) + .first(), + ctx.db + .query('aiReceiptUploads') + .withIndex('by_storage', (q) => q.eq('storageId', storageId)) + .take(2), + ctx.db + .query('avatars') + .withIndex('by_storage', (q) => q.eq('storageId', storageId)) + .first(), + ctx.db + .query('users') + .withIndex('by_avatarStorageId', (q) => q.eq('avatarStorageId', String(storageId))) + .first(), ]); - return Boolean(directMessage || groupMessage || attachment); + return Boolean( + receipt || + directMessage || + groupMessage || + attachment || + attachmentUpload || + receiptUploads.some((upload) => upload._id !== ignoredReceiptUploadId) || + avatar || + user, + ); } +/** Removes files with no database owner once any issued upload URL has expired. */ +export const purgeOrphanedStorage = internalMutation({ + args: { + cursor: v.optional(v.union(v.string(), v.null())), + olderThan: v.optional(v.number()), + }, + handler: async (ctx, { cursor, olderThan }) => { + const cutoff = olderThan ?? Date.now() - ORPHAN_STORAGE_GRACE_MS; + const page = await ctx.db.system + .query('_storage') + .order('asc') + .paginate({ cursor: cursor ?? null, numItems: ORPHAN_STORAGE_PAGE_SIZE }); + for (const file of page.page) { + if (file._creationTime >= cutoff) break; + if (!(await storageInUse(ctx, file._id))) await ctx.storage.delete(file._id); + } + const last = page.page[page.page.length - 1]; + if (!page.isDone && last && last._creationTime < cutoff) { + await ctx.scheduler.runAfter(0, internal.ai.receipts.purgeOrphanedStorage, { + cursor: page.continueCursor, + olderThan: cutoff, + }); + } + }, +}); + /** * Records the uploaded image on its ticket right after the upload, so an image whose parse * never arrives (app killed, connection lost, scan cancelled) can still be deleted. @@ -128,6 +199,7 @@ export const registerUpload = mutation({ upload.userId !== user._id || upload.usedAt !== undefined || upload.storageId !== undefined || + Date.now() - upload.createdAt > receiptUpload.ticketTtlMs || !file || file._creationTime < upload.createdAt - 1000 || (await storageInUse(ctx, storageId)) @@ -147,7 +219,7 @@ export const expireUpload = internalMutation({ if ( upload.usedAt === undefined && upload.storageId && - !(await storageInUse(ctx, upload.storageId)) && + !(await storageInUse(ctx, upload.storageId, upload._id)) && (await ctx.db.system.get('_storage', upload.storageId)) ) await ctx.storage.delete(upload.storageId); @@ -188,7 +260,7 @@ export const beginParse = internalMutation({ throw aiError('INVALID_UPLOAD_TICKET'); if ( (upload.storageId !== undefined && upload.storageId !== storageId) || - (await storageInUse(ctx, storageId)) + (await storageInUse(ctx, storageId, upload._id)) ) throw aiError('INVALID_UPLOAD_TICKET'); await ctx.db.patch(upload._id, { usedAt: now, storageId }); diff --git a/convex/ai/spreadsheet.ts b/convex/ai/spreadsheet.ts index a58c24b5..d5881bab 100644 --- a/convex/ai/spreadsheet.ts +++ b/convex/ai/spreadsheet.ts @@ -14,21 +14,46 @@ export const MAX_COLUMNS = 60; const MAX_UNZIPPED_BYTES = 60 * 1024 * 1024; const MAX_SHEETS = 12; -export type Sheet = { name: string; rows: string[][]; truncated: boolean }; +export type Sheet = { name: string; rows: string[][]; truncated: boolean; omittedSheets?: number }; // ---------- CSV ---------- /** The most likely delimiter in the first lines: comma, semicolon, tab or pipe. */ function detectDelimiter(text: string): string { - const sample = text.split(/\r?\n/, 5).join('\n'); + const candidates = [',', ';', '\t', '|']; + const records = new Map(candidates.map((delimiter) => [delimiter, [] as number[]])); + const counts = new Map(candidates.map((delimiter) => [delimiter, 0])); + let quoted = false; + let fieldStart = true; + for (let index = 0; index < text.length; index++) { + const char = text[index]!; + if (quoted) { + if (char === '"') { + if (text[index + 1] === '"') index++; + else quoted = false; + } + } else if (char === '"' && fieldStart) quoted = true; + else if (char === '\n' || char === '\r') { + for (const delimiter of candidates) records.get(delimiter)!.push(counts.get(delimiter)! + 1); + for (const delimiter of candidates) counts.set(delimiter, 0); + fieldStart = true; + if (char === '\r' && text[index + 1] === '\n') index++; + } else if (counts.has(char)) { + counts.set(char, counts.get(char)! + 1); + fieldStart = true; + } else fieldStart = false; + } + if (candidates.some((delimiter) => counts.get(delimiter)! > 0)) + for (const delimiter of candidates) records.get(delimiter)!.push(counts.get(delimiter)! + 1); let best = ','; - let bestCount = 0; - for (const candidate of [',', ';', '\t', '|']) { - const count = sample.split(candidate).length - 1; - if (count > bestCount) { - best = candidate; - bestCount = count; + let bestScore = 0; + for (const delimiter of candidates) { + const frequencies = new Map(); + for (const width of records.get(delimiter)!) { + if (width > 1) frequencies.set(width, (frequencies.get(width) ?? 0) + 1); } + const score = Math.max(0, ...frequencies.values()) * 100 + [...frequencies.values()].reduce((a, b) => a + b, 0); + if (score > bestScore) { best = delimiter; bestScore = score; } } return best; } @@ -142,15 +167,17 @@ function dateStyles(stylesXml: string | undefined): Set { } /** Excel serial day (1900 system) → `YYYY-MM-DD`. */ -export function excelSerialToIso(serial: number): string | null { - if (!Number.isFinite(serial) || serial < 1 || serial > 2_958_465) return null; - // Excel counts 1900-02-29 (which didn't exist); serial 60 and earlier are off by one. - const days = Math.floor(serial) - (serial > 60 ? 25_569 : 25_568); - const date = new Date(days * 86_400_000); - return date.toISOString().slice(0, 10); +export function excelSerialToIso(serial: number, date1904 = false): string | null { + if (!Number.isFinite(serial) || serial < 0 || serial > 2_958_465) return null; + if (date1904) + return new Date(Date.UTC(1904, 0, 1) + Math.floor(serial) * 86_400_000) + .toISOString() + .slice(0, 10); + const days = Math.floor(serial) - (serial >= 60 ? 25_569 : 25_568); + return new Date(days * 86_400_000).toISOString().slice(0, 10); } -function sheetRows(xml: string, shared: string[], dates: Set) { +function sheetRows(xml: string, shared: string[], dates: Set, date1904: boolean) { const rows: string[][] = []; let truncated = false; for (const rowMatch of xml.matchAll(/]*)>([\s\S]*?)<\/row>|]*\/>/g)) { @@ -186,7 +213,7 @@ function sheetRows(xml: string, shared: string[], dates: Set) { else if (raw !== undefined) { const style = Number(attr(tag, 's') ?? '-1'); const number = Number(raw); - value = dates.has(style) ? (excelSerialToIso(number) ?? raw) : raw; + value = dates.has(style) ? (excelSerialToIso(number, date1904) ?? raw) : raw; } while (cells.length < column) cells.push(''); cells[column] = value.trim(); @@ -220,7 +247,7 @@ export function readXlsx(bytes: Uint8Array): Sheet[] { const shared = [...(text('xl/sharedStrings.xml') ?? '').matchAll(/([\s\S]*?)<\/si>/g)].map( (match) => itemText(match[1]!), ); - const dates = dateStyles(text('xl/styles.xml')); + const date1904 = /]*\bdate1904="(?:1|true)"/i.test(workbook); const rels = new Map(); for (const match of (text('xl/_rels/workbook.xml.rels') ?? '').matchAll( /]*>/g, @@ -230,16 +257,26 @@ export function readXlsx(bytes: Uint8Array): Sheet[] { if (id && target) rels.set(id, target.replace(/^\/?(xl\/)?/, 'xl/')); } const sheets: Sheet[] = []; + const dates = dateStyles(text('xl/styles.xml')); + let omittedSheets = 0; for (const match of workbook.matchAll(/]*>/g)) { - if (sheets.length >= MAX_SHEETS) break; + if (sheets.length >= MAX_SHEETS) { + omittedSheets += 1; + continue; + } const name = decodeXml(attr(match[0], 'name') ?? `Sheet${sheets.length + 1}`); const relId = attr(match[0], 'r:id'); const path = (relId && rels.get(relId)) || `xl/worksheets/sheet${sheets.length + 1}.xml`; const xml = text(path); if (!xml) continue; - const { rows, truncated } = sheetRows(xml, shared, dates); + const { rows, truncated } = sheetRows(xml, shared, dates, date1904); sheets.push({ name, rows, truncated }); } + if (omittedSheets > 0) { + const lastSheet = sheets[MAX_SHEETS - 1]; + if (lastSheet) lastSheet.omittedSheets = omittedSheets; + } + if (!sheets.length) throw new Error('INVALID_SPREADSHEET'); return sheets; } @@ -255,17 +292,25 @@ function csvCell(value: string): string { * then a note with the total so the model knows to use the import tool for the full data. */ export function sheetForPrompt(sheet: Sheet, maxChars: number): string { - const nonEmpty = sheet.rows.filter((row) => row.some((cell) => cell !== '')); - const lines: string[] = []; - let used = 0; + const budget = Math.max(0, maxChars); + if (!budget) return ''; + const rows = sheet.rows.filter((row) => row.some((cell) => cell !== '')); + const lines = rows.map((row) => row.map(csvCell).join(',')); + const disclosure = sheet.truncated + ? '… parser limit reached; additional data may be missing' + : sheet.omittedSheets + ? `… ${sheet.omittedSheets} additional sheets not parsed` + : '… rows omitted; use import tool for complete data'; + let output = ''; let shown = 0; - for (const row of nonEmpty) { - const line = row.map(csvCell).join(','); - if (used + line.length + 1 > maxChars && shown > 0) break; - lines.push(line); - used += line.length + 1; + for (const line of lines) { + const next = output ? `${output}\n${line}` : line; + if (next.length + (shown + 1 < lines.length || sheet.truncated || sheet.omittedSheets ? disclosure.length : 0) > budget) + break; + output = next; shown++; } - const more = nonEmpty.length - shown + (sheet.truncated ? 1 : 0); - return `${lines.join('\n')}${more > 0 ? `\n… (${nonEmpty.length}${sheet.truncated ? '+' : ''} rows in total; ${more} not shown)` : ''}`; + if (shown === lines.length && !sheet.truncated && !sheet.omittedSheets) return output; + if (!output) return disclosure.slice(0, budget); + return `${output.slice(0, Math.max(0, budget - disclosure.length))}${disclosure}`.slice(0, budget); } diff --git a/convex/crons.ts b/convex/crons.ts index 1c96cbd4..61f58cf0 100644 --- a/convex/crons.ts +++ b/convex/crons.ts @@ -14,4 +14,12 @@ crons.hourly( {}, ); +// Remove unreferenced storage files only after issued upload URLs have expired. +crons.daily( + 'purge unreferenced storage', + { hourUTC: 4, minuteUTC: 15 }, + internal.ai.receipts.purgeOrphanedStorage, + {}, +); + export default crons; diff --git a/convex/schema.ts b/convex/schema.ts index 14698a09..042096a4 100644 --- a/convex/schema.ts +++ b/convex/schema.ts @@ -62,7 +62,7 @@ export default defineSchema({ .index('email', ['email']) .index('by_identityId', ['identityId']) .index('by_username', ['username']) - .index('by_phone', ['phone']), + .index('by_phone', ['phone']).index('by_avatarStorageId', ['avatarStorageId']), userSettings: defineTable({ userId: v.id('users'), currency, @@ -248,7 +248,7 @@ export default defineSchema({ mimeType: v.string(), size: v.number(), createdAt: timestamp, - }).index('by_transaction', ['transactionId']), + }).index('by_transaction', ['transactionId']).index('by_storage', ['storageId']), auditEvents: defineTable({ actorId: v.id('users'), entityType: v.string(), @@ -846,6 +846,16 @@ export default defineSchema({ .index('by_conversation', ['conversationId']) .index('by_storage', ['storageId']) .index('by_expiresAt', ['expiresAt']), + /** Single-use tickets for FinAI uploads, cleaned up after the registration window. */ + finaiAttachmentUploads: defineTable({ + ticket: v.string(), + userId: v.id('users'), + createdAt: timestamp, + storageId: v.optional(v.id('_storage')), + }) + .index('by_ticket', ['ticket']) + .index('by_createdAt', ['createdAt']) + .index('by_storage', ['storageId']), finaiMessages: defineTable({ conversationId: v.id('finaiConversations'), userId: v.id('users'), @@ -896,7 +906,8 @@ export default defineSchema({ storageId: v.optional(v.id('_storage')), }) .index('by_ticket', ['ticket']) - .index('by_user_createdAt', ['userId', 'createdAt']), + .index('by_user_createdAt', ['userId', 'createdAt']) + .index('by_storage', ['storageId']), avatars: defineTable({ avatarId: v.string(), gender: v.union(v.literal('neutral'), v.literal('male'), v.literal('female')), @@ -906,5 +917,6 @@ export default defineSchema({ updatedAt: timestamp, }) .index('by_avatarId', ['avatarId']) - .index('by_gender_avatarId', ['gender', 'avatarId']), + .index('by_gender_avatarId', ['gender', 'avatarId']) + .index('by_storage', ['storageId']), }); diff --git a/tests/convex/finai-attachments-parse.test.ts b/tests/convex/finai-attachments-parse.test.ts index 9b883bdb..279abf3c 100644 --- a/tests/convex/finai-attachments-parse.test.ts +++ b/tests/convex/finai-attachments-parse.test.ts @@ -1,6 +1,12 @@ import { describe, expect, it } from 'vitest'; import { strToU8, zipSync } from 'fflate'; -import { excelSerialToIso, parseCsv, readXlsx, sheetForPrompt } from '../../convex/ai/spreadsheet'; +import { readSheets } from '../../convex/ai/attachmentContent'; +import { + excelSerialToIso, + parseCsv, + readXlsx, + sheetForPrompt, +} from '../../convex/ai/spreadsheet'; import { detectDateFormat, mapImportRows, @@ -57,6 +63,11 @@ describe('spreadsheet readers', () => { expect(() => readXlsx(zipSync({ 'hello.txt': strToU8('hi') }))).toThrow('INVALID_SPREADSHEET'); expect(() => readXlsx(new Uint8Array([1, 2, 3]))).toThrow(); }); + it('dispatches ZIP signatures, not arbitrary PK-prefixed CSV', () => { + expect(readSheets(strToU8('PK\u0005\u0006,date'), 'fake.csv')[0]!.rows).toEqual([ + ['PK\u0005\u0006', 'date'], + ]); + }); it('parses CSV with quotes, embedded newlines, BOM and a detected delimiter', () => { expect(parseCsv('a,b\n"x, y","say ""hi"""\n"multi\nline",2\n').rows).toEqual([ @@ -69,6 +80,32 @@ describe('spreadsheet readers', () => { ['01/02/2026', '12,50'], ]); }); + it('detects delimiters outside quoted fields and favors consistent widths', () => { + expect(parseCsv('"a,;|";b;c\n"x,y;|";2;3\nlast;4\n').rows[0]).toEqual(['a,;|', 'b', 'c']); + expect(parseCsv('a;b;c\n1;2;3\n4;5\n').rows[0]).toEqual(['a', 'b', 'c']); + }); + + it('handles serial zero and the workbook 1904 date epoch', () => { + expect(excelSerialToIso(0)).toBe('1899-12-31'); + expect(excelSerialToIso(0, true)).toBe('1904-01-01'); + expect(excelSerialToIso(1, true)).toBe('1904-01-02'); + }); + it('keeps oversized first rows within the prompt budget and signals omissions', () => { + const rendered = sheetForPrompt( + { name: 'large', rows: [['x'.repeat(300)], ['later']], truncated: false }, + 24, + ); + expect(rendered.length).toBeLessThanOrEqual(24); + expect(rendered).toContain('…'); + }); + it('converts date-styled serial zero with the workbook date1904 epoch', () => { + const bytes = zipSync({ + 'xl/workbook.xml': strToU8(''), + 'xl/worksheets/sheet1.xml': strToU8('0'), + 'xl/styles.xml': strToU8(''), + }); + expect(readXlsx(bytes)[0]!.rows).toEqual([['1904-01-01']]); + }); it('converts Excel serials across the 1900 leap-year bug', () => { expect(excelSerialToIso(1)).toBe('1900-01-01'); diff --git a/tests/convex/finai-attachments.test.ts b/tests/convex/finai-attachments.test.ts index 6f527a45..7677a767 100644 --- a/tests/convex/finai-attachments.test.ts +++ b/tests/convex/finai-attachments.test.ts @@ -4,6 +4,7 @@ import { api, internal } from '../../convex/_generated/api'; import type { Id } from '../../convex/_generated/dataModel'; import schema from '../../convex/schema'; import { aiErrorCode } from '../../convex/ai/errors'; +import { providerChat } from '../../convex/ai/providers'; const modules = import.meta.glob('../../convex/**/*.ts'); @@ -95,8 +96,15 @@ async function fixture() { return { ownerId, outsiderId, accountId, foodId }; }); const as = (id: string) => t.withIdentity({ subject: `${id}|session` }); - const upload = (body: string | Uint8Array, type: string) => - t.run((ctx) => ctx.storage.store(new Blob([body], { type }))); + const upload = async ( + body: string | Uint8Array, + type: string, + actor = as(ids.ownerId), + ) => { + const { ticket } = await actor.mutation(api.ai.attachments.generateUploadUrl, {}); + const storageId = await t.run((ctx) => ctx.storage.store(new Blob([body], { type }))); + return { ticket, storageId }; + }; return { t, ids, owner: as(ids.ownerId), outsider: as(ids.outsiderId), upload }; } @@ -105,12 +113,22 @@ const PNG = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2 const CSV = 'Date,Description,Amount,Category\n2026-01-05,Coffee,-4.50,Food\n2026-01-06,Salary,2500,\n2026-01-07,Lunch,-12,Dining\nbad,Row,1,\n'; +type UploadedFile = { ticket: string; storageId: Id<'_storage'> }; + +async function register( + owner: Awaited>['owner'], + file: UploadedFile, + name: string, +) { + return owner.mutation(api.ai.attachments.register, { ...file, name }); +} + async function registered( owner: Awaited>['owner'], - storageId: Id<'_storage'>, + file: UploadedFile, name: string, ) { - const result = await owner.mutation(api.ai.attachments.register, { storageId, name }); + const result = await register(owner, file, name); if (!('attachment' in result) || !result.attachment) throw new Error(`register failed: ${JSON.stringify(result)}`); return result.attachment; @@ -124,15 +142,15 @@ describe('FinAI attachments', () => { const exe = await upload('MZ', 'application/octet-stream'); expect( - await owner.mutation(api.ai.attachments.register, { storageId: exe, name: 'run.exe' }), + await register(owner, exe, 'run.exe'), ).toEqual({ error: 'UNSUPPORTED_FILE', }); - expect(await t.run((ctx) => ctx.db.system.get('_storage', exe))).toBeNull(); + expect(await t.run((ctx) => ctx.db.system.get('_storage', exe.storageId))).toBeNull(); const big = await upload(new Uint8Array(10 * 1024 * 1024 + 1), 'text/csv'); expect( - await owner.mutation(api.ai.attachments.register, { storageId: big, name: 'big.csv' }), + await register(owner, big, 'big.csv'), ).toEqual({ error: 'FILE_TOO_LARGE', }); @@ -141,7 +159,7 @@ describe('FinAI attachments', () => { await registered(owner, csv, 'bank.csv'); expect( await codeOf( - owner.mutation(api.ai.attachments.register, { storageId: csv, name: 'again.csv' }), + register(owner, csv, 'again.csv'), ), ).toBe('INVALID_UPLOAD'); }); @@ -189,6 +207,28 @@ describe('FinAI attachments', () => { expect(history).not.toContain('inlineData'); }); + it.each(['image/heic', 'image/heif'])( + 'rejects %s before sending it to Anthropic', + async (mimeType) => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + const chat = providerChat({ + provider: 'anthropic', + apiKey: 'test-key', + model: 'claude-test', + }); + + await expect( + chat({ + role: 'chat', + parts: [], + contents: [{ role: 'user', parts: [{ inlineData: { mimeType, data: 'aGVpYw==' } }] }], + }), + ).rejects.toThrow('Anthropic does not support HEIC/HEIF'); + expect(fetchMock).not.toHaveBeenCalled(); + }, + ); + it("refuses someone else's or already-sent attachments", async () => { const { owner, outsider, upload } = await fixture(); const sheet = await registered(owner, await upload(CSV, 'text/csv'), 'bank.csv'); @@ -262,6 +302,49 @@ describe('FinAI attachments', () => { ['Salary', 'income', 250_000n, null, ids.accountId], ]); }); + it('retries a partially committed import after stale-running without duplicating its first row', async () => { + const { t, owner, upload } = await fixture(); + const csv = 'Date,Description,Amount\n2026-01-05,First,-4.50\n2026-01-06,Second,-2.00\n'; + const sheet = await registered(owner, await upload(csv, 'text/csv'), 'retry.csv'); + mockGemini([ + { + call: { + name: 'propose_import_transactions', + args: { attachmentId: sheet.id, date: 'Date', description: 'Description', amount: 'Amount' }, + }, + }, + { text: 'Confirm to import.' }, + ]); + const { conversationId, replyId } = await owner.action(api.ai.assistant.send, { + text: 'import', + attachmentIds: [sheet.id], + }); + const messages = await owner.query(api.ai.assistant.messages, { conversationId, paginationOpts: page }); + const card = messages.page.find((row) => row.id === replyId)!.actions[0]!; + const originalPayload = await t.run(async (ctx) => { + const actionRow = await ctx.db.get(card.id as Id<'finaiActions'>); + const payload = JSON.parse(actionRow!.payload) as { rows: unknown[][] }; + payload.rows[1]![2] = 'invalid'; + await ctx.db.patch(card.id as Id<'finaiActions'>, { payload: JSON.stringify(payload) }); + return actionRow!.payload; + }); + expect(await owner.action(api.ai.actions.confirm, { actionId: card.id as Id<'finaiActions'> })).toMatchObject({ + status: 'failed', + }); + expect(await t.run((ctx) => ctx.db.query('transactions').collect())).toHaveLength(1); + await t.run(async (ctx) => { + const payload = JSON.parse(originalPayload) as { rows: unknown[][] }; + payload.rows[1]![2] = '200'; + await ctx.db.patch(card.id as Id<'finaiActions'>, { + payload: JSON.stringify(payload), + decidedAt: Date.now() - 3 * 60 * 1000, + }); + }); + expect(await owner.action(api.ai.actions.confirm, { actionId: card.id as Id<'finaiActions'> })).toMatchObject({ + status: 'done', + }); + expect(await t.run((ctx) => ctx.db.query('transactions').collect())).toHaveLength(2); + }); it('reports wrong column names with the real headers', async () => { const { owner, upload } = await fixture(); diff --git a/tests/convex/storage-cleanup.test.ts b/tests/convex/storage-cleanup.test.ts new file mode 100644 index 00000000..b62bc142 --- /dev/null +++ b/tests/convex/storage-cleanup.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from 'vitest'; +import { convexTest } from 'convex-test'; +import { internal } from '../../convex/_generated/api'; +import schema from '../../convex/schema'; + +const modules = import.meta.glob('../../convex/**/*.ts'); + +describe('orphaned Convex storage cleanup', () => { + it('deletes unreferenced files and preserves every app-owned storage reference', async () => { + const t = convexTest(schema, modules); + const ids = await t.run(async (ctx) => { + const now = Date.now(); + const ownerId = await ctx.db.insert('users', { + identityId: 'storage-cleanup-owner', + email: 'storage-cleanup@example.com', + emailVerificationTime: 1, + displayName: 'Storage cleanup owner', + }); + const accountId = await ctx.db.insert('accounts', { + ownerId, + name: 'Wallet', + type: 'cash', + currency: 'INR', + openingBalanceMinor: 0n, + isIncludedInTotal: true, + createdAt: now, + updatedAt: now, + }); + const categoryId = await ctx.db.insert('categories', { + ownerId, + name: 'Food', + kind: 'expense', + isSystem: false, + sortOrder: 1, + createdAt: now, + updatedAt: now, + }); + const transactionId = await ctx.db.insert('transactions', { + ownerId, + accountId, + type: 'expense', + amountMinor: 500n, + currency: 'INR', + categoryId: String(categoryId), + title: 'Receipt test', + occurredAt: now, + status: 'posted', + createdAt: now, + updatedAt: now, + }); + const orphan = await ctx.storage.store(new Blob(['orphan'], { type: 'text/plain' })); + const userAvatar = await ctx.storage.store(new Blob(['user avatar'], { type: 'image/png' })); + const catalogAvatar = await ctx.storage.store(new Blob(['catalog avatar'], { type: 'image/png' })); + const receipt = await ctx.storage.store(new Blob(['receipt'], { type: 'image/png' })); + await ctx.db.patch(ownerId, { avatarStorageId: String(userAvatar) }); + await ctx.db.insert('avatars', { + avatarId: 'storage-cleanup-avatar', + gender: 'neutral', + storageId: catalogAvatar, + createdAt: now, + updatedAt: now, + }); + await ctx.db.insert('receipts', { + transactionId, + ownerId, + storageId: receipt, + mimeType: 'image/png', + size: 7, + createdAt: now, + }); + return { orphan, userAvatar, catalogAvatar, receipt }; + }); + + await t.mutation(internal.ai.receipts.purgeOrphanedStorage, { + olderThan: Date.now() + 60_000, + }); + + const files = await t.run(async (ctx) => ({ + orphan: await ctx.db.system.get('_storage', ids.orphan), + userAvatar: await ctx.db.system.get('_storage', ids.userAvatar), + catalogAvatar: await ctx.db.system.get('_storage', ids.catalogAvatar), + receipt: await ctx.db.system.get('_storage', ids.receipt), + })); + expect(files.orphan).toBeNull(); + expect(files.userAvatar).not.toBeNull(); + expect(files.catalogAvatar).not.toBeNull(); + expect(files.receipt).not.toBeNull(); + }); +});