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
39 changes: 19 additions & 20 deletions apps/mobile/hooks/useFinaiActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number | null>(null);
const seenReplyIds = React.useRef<Set<string> | null>(null);
const onReplyRef = React.useRef(onReply);
React.useEffect(() => {
onReplyRef.current = onReply;
});

const latest = React.useMemo<FinaiLatestReply | null>(
() =>
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,
Expand Down
46 changes: 27 additions & 19 deletions apps/web/components/finance/FinaiLauncher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,46 +19,54 @@ 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<HTMLDivElement>(null);
const buttonRef = React.useRef<HTMLButtonElement>(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);
update();
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.
Expand Down Expand Up @@ -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;
Expand Down
39 changes: 39 additions & 0 deletions apps/web/lib/finai/activityTracker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import type { FinaiLatestReply } from '@finapp/ui/ai/finai';

export type FinaiActivityTracker = {
userId: string | null;
seenReplyIds: Set<string> | 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;
}
32 changes: 10 additions & 22 deletions apps/web/lib/finai/useFinaiActivity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number | null>(null);
const tracker = React.useRef<FinaiActivityTracker>({ userId, seenReplyIds: null });
const onReplyRef = React.useRef(onReply);
React.useEffect(() => {
onReplyRef.current = onReply;
});

const latest = React.useMemo<FinaiLatestReply | null>(
() =>
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,
Expand Down
48 changes: 30 additions & 18 deletions convex/ai/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,43 +67,51 @@ 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))
.order('desc')
.take(50);
const now = Date.now();
const unread = rows.filter((row) => row.unreadAt !== undefined);
const newest = unread.reduce<Doc<'finaiConversations'> | 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,
};
},
});
Expand Down Expand Up @@ -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')
Expand Down
60 changes: 52 additions & 8 deletions convex/ai/assistantTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -218,25 +247,40 @@ export const assistantTools: FinaiTool[] = [
// Filters apply after pagination, so walk raw pages until enough rows match.
type Row = FunctionReturnType<typeof api.mcp.listTransactions>['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<typeof api.mcp.listTransactions> = 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: {
Expand Down
Loading
Loading