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
4 changes: 2 additions & 2 deletions apps/mobile/hooks/useFinaiAssistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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' };
Expand Down
4 changes: 2 additions & 2 deletions apps/web/lib/finai/useFinaiAssistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function useFinaiAssistant(enabled: boolean, initialId: string | null = n
const discard = useMutation(api.ai.attachments.discard);
const composer = useComposerFiles<File>({
upload: async (file: PickedFile<File>) => {
const { uploadUrl: url } = await uploadUrl({});
const { uploadUrl: url, ticket } = await uploadUrl({});
const blob = file.source;
const response = await fetch(url, {
method: 'POST',
Expand All @@ -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' };
Expand Down
6 changes: 5 additions & 1 deletion convex/ai/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Comment on lines +311 to +312

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Stop showing failed imports as still running

When an import fails with a known error—such as a deleted account/category or an invalid row—the action has already returned { status: 'failed' }, but this patch persists it as running. actionViews therefore renders the card as “Saving…” until staleRunningMs elapses and then makes it retryable without cancellation; permanent failures repeat this cycle indefinitely instead of displaying the stored error as a terminal failure. Reserve the stale-running retry path for genuinely interrupted executions or introduce an explicit retryable failure state.

Useful? React with 👍 / 👎.

});
return { status: 'failed', errorCode };
}
},
Expand Down
5 changes: 4 additions & 1 deletion convex/ai/attachmentContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[] {
Expand Down
55 changes: 46 additions & 9 deletions convex/ai/attachments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,33 +94,51 @@ 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),
};
},
});

/**
* 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 ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Start the registration window when the upload finishes

On a slow connection, a valid attachment is rejected once 15 minutes have elapsed since the upload URL was requested, even if the object only just reached storage. A 10 MB upload can exceed that interval on a constrained mobile network, and this check now uses the ticket creation time rather than the stored file's _creationTime, contrary to the registration window's intended post-upload grace period.

Useful? React with 👍 / 👎.

!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 =
Expand All @@ -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', {
Expand All @@ -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);
Expand Down
8 changes: 8 additions & 0 deletions convex/ai/importTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
15 changes: 15 additions & 0 deletions convex/ai/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>[] }[] = [];
Expand Down Expand Up @@ -409,6 +423,7 @@ async function anthropicChat(
config: ProviderConfig,
options: ChatStreamOptions,
): Promise<ChatStreamResult> {
assertAnthropicImageTypes(options.contents);
const defaults = aiGeneration[options.role];
const body = {
model: config.model,
Expand Down
86 changes: 79 additions & 7 deletions convex/ai/receipts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<boolean> {
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<boolean> {
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))
Expand All @@ -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.
Expand All @@ -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))
Expand All @@ -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);
Expand Down Expand Up @@ -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 });
Expand Down
Loading
Loading