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
27 changes: 22 additions & 5 deletions apps/web/app/profile/[username]/PersonPageClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,9 @@ export default function PersonPage({ handle, profile, profileUnavailable }: Pers
groupIdAliases.has(item.groupId) &&
item.type === 'expense' &&
item.status === 'posted' &&
item.deletedAt === undefined,
item.deletedAt === undefined &&
Number(item.occurredAt ?? 0) >= startAt &&
Number(item.occurredAt ?? 0) < endAt,
Comment on lines +242 to +243

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 Recompute the recent-expense window after module initialization

The newly added filter uses startAt and endAt, which are computed once at module initialization. If the SPA remains loaded and a shared expense is created later, or the user returns to this page without a hard reload, its occurredAt can be at or beyond the stale endAt, so it disappears from the “Last 90 days” count and list even though local records contain it. Compute the bounds per page load/render or refresh them when the range is fetched.

Useful? React with 👍 / 👎.

)
.sort((left, right) => Number(right.occurredAt ?? 0) - Number(left.occurredAt ?? 0))
: [];
Expand Down Expand Up @@ -285,10 +287,22 @@ export default function PersonPage({ handle, profile, profileUnavailable }: Pers
sharedGroups.length === 1
? `/split/new?groupId=${encodeURIComponent(idOf(sharedGroups[0]!))}`
: '/split/new';
const balanceError =
rangeState === 'error' ||
Boolean(
groupsError ||
membersError ||
transactionsError ||
payersError ||
participantsError ||
settlementsError,
);
const balanceLabel = !balanceAvailable
? sharedGroups.length
? 'Loading balance…'
: 'No shared groups'
? balanceError
? 'Balance unavailable'
: sharedGroups.length
? 'Loading balance…'
: 'No shared groups'
: bilateralBalance === 0n
? 'You’re even'
: bilateralBalance > 0n
Expand Down Expand Up @@ -444,7 +458,10 @@ export default function PersonPage({ handle, profile, profileUnavailable }: Pers
</Link>
</>
) : null}
{person.id ? (
{person.id &&
(sharedGroups.length > 0 ||
status === 'friends' ||
Boolean(analytics?.conversationId)) ? (
Comment on lines +461 to +464

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 Honor server-reported shared groups when gating analytics

If relationship.sharedGroups reports a shared group but the local group/member cache is still loading, incomplete, or unavailable, personAnalytics is valid and groupCount is nonzero, yet this condition checks only sharedGroups.length. For people who are neither friends nor direct-message contacts, that hides the analytics link despite the server-confirmed shared relationship; gate on the combined/server group result instead.

Useful? React with 👍 / 👎.

<Link
className="profile-icon-button"
href={`/network/person/${encodeURIComponent(person.id)}`}
Expand Down
7 changes: 2 additions & 5 deletions apps/web/lib/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,6 @@ export async function markAllNotificationsRead(
export function useUnreadChatCount(): number {
const { userId, isConnected } = useBrowserSync();
const live = Boolean(userId && isConnected);
const people = useQuery(api.social.queries.peopleHub, live ? {} : 'skip');
const groups = useQuery(api.groups.queries.chatUnreadCounts, live ? {} : 'skip');
const direct = people?.reduce((sum, person) => sum + person.unreadCount, 0) ?? 0;
const grouped = groups ? Object.values(groups).reduce((sum, count) => sum + count, 0) : 0;
return direct + grouped;
const unread = useQuery(api.social.queries.peopleHubUnreadTotal, live ? {} : 'skip');
return unread ?? 0;
}
208 changes: 173 additions & 35 deletions convex/social/queries.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { v } from 'convex/values';
import { query } from '../_generated/server';
import type { Doc, Id } from '../_generated/dataModel';
import { getAnalyticsDayRange } from '../analytics/domain';
import { getOptionalUser } from '../shared/auth';
import { loadReadPointers, type ChatScope } from '../shared/chat';
import { avatarUrlForUser } from '../avatars/helpers';

const safeProfile = (user: Doc<'users'>) => ({
Expand Down Expand Up @@ -348,12 +350,20 @@
...friendHigh.map((row) => String(row.userLowId)),
...conversationByPeer.keys(),
]);
const candidates = [...peerIds]
.sort(
(a, b) =>
(conversationByPeer.get(b)?.updatedAt ?? 0) -
(conversationByPeer.get(a)?.updatedAt ?? 0) ||
a.localeCompare(b),
)
.slice(0, PEOPLE_HUB_LIMIT * 2);
Comment on lines +353 to +360

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 Rank unread conversations before truncating candidates

For accounts with more than 120 peers, this truncates solely by conversation.updatedAt before unread counts are loaded. An older conversation with unread messages is therefore omitted entirely when 120 newer conversations exist, even though the query's documented and final ordering puts unread conversations first; the aggregate badge can indicate unread messages while the People hub offers no corresponding row. Include unread state in candidate selection or avoid truncating before the unread-first ranking.

Useful? React with 👍 / 👎.

const now = Date.now();
const rows = await Promise.all(
[...peerIds].slice(0, PEOPLE_HUB_LIMIT * 2).map(async (rawId) => {
candidates.map(async (rawId) => {
const userId = rawId as Id<'users'>;
const conversation = conversationByPeer.get(rawId);
const [user, settings, presence, pointer] = await Promise.all([
const [user, settings, presence] = await Promise.all([
ctx.db.get(userId),
ctx.db
.query('userSettings')
Expand All @@ -363,30 +373,43 @@
.query('presence')
.withIndex('by_user', (q) => q.eq('userId', userId))
.unique(),
conversation
? ctx.db
.query('chatReadPointers')
.withIndex('by_scope_user', (q) =>
q
.eq('scopeType', 'direct')
.eq('scopeId', conversation._id)
.eq('userId', actor._id),
)
.unique()
: Promise.resolve(null),
]);
if (!user || user.deletedAt !== undefined) return null;
let unreadCount = 0;
let unreadCapped = false;
if (conversation) {
const lastReadAt = pointer?.lastReadAt ?? 0;
const recent = await ctx.db
const pointers = await loadReadPointers(
ctx,
{ type: 'direct', id: conversation._id },
[actor._id],
);
const lastReadAt = pointers.get(actor._id) ?? 0;
const messageQuery = ctx.db
.query('directMessages')
.withIndex('by_conversation_createdAt', (q) =>
q.eq('conversationId', conversation._id).gt('createdAt', lastReadAt),
)
.order('desc')
.take(PEOPLE_HUB_UNREAD_CAP + 1);
unreadCount = recent.filter((message) => message.senderId !== actor._id).length;
.order('desc');
let cursor: string | null = null;
let done = false;
while (!done && !unreadCapped) {
const page = await messageQuery.paginate({ numItems: 50, cursor });

Check failure on line 396 in convex/social/queries.ts

View workflow job for this annotation

GitHub Actions / validate

../../tests/convex/people-hub.test.ts > people hub > ranks conversations before limiting hub candidates

Error: Only a single paginated query (`.paginate()`) is allowed per function execution. Calling `.paginate()` more than once in a single Convex function fails at runtime in a deployed backend. This is a Convex limit: https://docs.convex.dev/database/pagination ❯ performAsyncSyscall ../../node_modules/convex/src/server/impl/syscall.ts:52:10 ❯ QueryImpl.paginate ../../node_modules/convex/src/server/impl/query_impl.ts:297:6 ❯ ../../convex/social/queries.ts:396:26 ❯ handler ../../convex/social/queries.ts:362:18 ❯ invokeFunction ../../node_modules/convex/src/server/impl/registration_impl.ts:90:13 ❯ invokeQuery ../../node_modules/convex/src/server/impl/registration_impl.ts:350:17 ❯ runQueryWithHandler ../../node_modules/convex-test/dist/index.js:1708:31 ❯ Object.queryFromPath ../../node_modules/convex-test/dist/index.js:1767:32

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Replace repeated pagination in the hub query

Convex permits only one .paginate() invocation during a query execution, but this call runs once per conversation inside candidates.map; a user with two direct conversations therefore hits an exception on the second invocation. A single conversation can also fail when the loop requests a second page after scanning 50 mostly self-sent messages. As a result, peopleHub and the network screens backed by it fail for ordinary multi-conversation accounts; use bounded non-paginated reads or paginate across separate query executions.

Useful? React with 👍 / 👎.

for (const message of page.page) {
const expiresAt = 'expiresAt' in message ? message.expiresAt : undefined;
if (
message.senderId !== actor._id &&
!(typeof expiresAt === 'number' && expiresAt <= now)
) {
unreadCount += 1;
if (unreadCount > PEOPLE_HUB_UNREAD_CAP) {
unreadCapped = true;
break;
}
}
}
cursor = page.continueCursor;
done = page.isDone;
}
}
const showActive = settings?.showActive ?? true;
const showLastSeen = settings?.showLastSeen ?? true;
Expand All @@ -396,7 +419,7 @@
conversationId: conversation?._id ?? null,
lastMessageAt: conversation?.updatedAt ?? null,
unreadCount: Math.min(unreadCount, PEOPLE_HUB_UNREAD_CAP),
unreadCapped: unreadCount > PEOPLE_HUB_UNREAD_CAP,
unreadCapped,
active: showActive ? (presence?.activeUntil ?? 0) > now : null,
lastSeenAt: showLastSeen ? (presence?.lastSeenAt ?? null) : null,
};
Expand All @@ -413,27 +436,127 @@
.slice(0, PEOPLE_HUB_LIMIT);
},
});
export const peopleHubUnreadTotal = query({
args: {},
handler: async (ctx) => {
const actor = await getOptionalUser(ctx);
if (!actor || actor.deletedAt !== undefined) return 0;
const [convLow, convHigh, memberships] = await Promise.all([
ctx.db
.query('directConversations')
.withIndex('by_pair', (q) => q.eq('userLowId', actor._id))
.collect(),
ctx.db
.query('directConversations')
.withIndex('by_high', (q) => q.eq('userHighId', actor._id))
.collect(),
ctx.db
.query('groupMembers')
.withIndex('by_user', (q) => q.eq('userId', actor._id))
.collect(),
]);
const scopes: ChatScope[] = [
...[...convLow, ...convHigh].map((conversation) => ({
type: 'direct' as const,
id: conversation._id,
})),
Comment on lines +459 to +462

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 Exclude deleted peers from the unread aggregate

When the other participant has soft-deleted their account, their conversation and messages remain in the database, so this scope construction still includes their unread messages. peopleHub filters that deleted user out, leaving no visible conversation through which the viewer can discover or clear the count, while the People badge remains nonzero. Resolve each conversation's peer and omit deleted users, matching the hub's visibility rules.

Useful? React with 👍 / 👎.

...memberships.map((membership) => ({ type: 'group' as const, id: membership.groupId })),
];
const now = Date.now();
const counts = await Promise.all(
scopes.map(async (scope) => {
const pointers = await loadReadPointers(ctx, scope, [actor._id]);
const lastReadAt = pointers.get(actor._id) ?? 0;
const messages =
scope.type === 'direct'
? await ctx.db
.query('directMessages')
.withIndex('by_conversation_createdAt', (q) =>
q.eq('conversationId', scope.id).gt('createdAt', lastReadAt),
)
.collect()

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 Keep unread-total reads bounded

When an account has accumulated enough unread messages, this .collect() loads every unread document in every DM, while the group branch does the same for every group. The previous badge queries bounded each thread's reads, but this replacement can exceed Convex's per-query document or byte limits, causing the globally mounted unread-count query to fail for busy or long-unread accounts. Preserve bounded reads or maintain a denormalized aggregate rather than collecting the complete history.

Useful? React with 👍 / 👎.

: await ctx.db
.query('groupMessages')
.withIndex('by_group_createdAt', (q) =>
q.eq('groupId', scope.id).gt('createdAt', lastReadAt),
)
.collect();
let unread = 0;
for (const message of messages) {
if (
message.senderId !== actor._id &&
!(
'expiresAt' in message &&
typeof message.expiresAt === 'number' &&
message.expiresAt <= now
)
) {
unread += 1;
}
}
return unread;
}),
);
return counts.reduce((sum, count) => sum + count, 0);
},
});

const ACTIVITY_DAYS = 30;
const DAY_MS = 24 * 60 * 60 * 1000;
/** Messages read per conversation for analytics at most; older ones fall outside the window. */
const ACTIVITY_MESSAGE_LIMIT = 2000;

function activityDayStarts(now: number, timeZone: string | undefined, offsetMinutes: number) {
if (timeZone) {
const current = getAnalyticsDayRange(now, timeZone);
const starts = new Array<number>(ACTIVITY_DAYS);
starts[ACTIVITY_DAYS - 1] = current.startAt;
for (let index = ACTIVITY_DAYS - 2; index >= 0; index -= 1) {
starts[index] = getAnalyticsDayRange(starts[index + 1]! - 1, timeZone).startAt;
}
return { starts, endAt: current.endAt };
}
const offset = offsetMinutes * 60_000;
const todayStart = Math.floor((now - offset) / DAY_MS) * DAY_MS + offset;
return {
starts: Array.from(
{ length: ACTIVITY_DAYS },
(_, index) => todayStart - (ACTIVITY_DAYS - index - 1) * DAY_MS,
),
endAt: todayStart + DAY_MS,
};
}

function activityDayIndex(starts: readonly number[], timestamp: number) {
let low = 0;
let high = starts.length;
while (low < high) {
const middle = (low + high) >>> 1;
if (starts[middle]! <= timestamp) low = middle + 1;
else high = middle;
}
return low - 1;
}

/**
* One person's analytics with you: direct messages per day for the last 30 days (sent and
* received), message mix, your shared groups and friendship status. Only for people you
* already share a conversation, friendship or group with.
*/
export const personAnalytics = query({
args: { userId: v.id('users'), tzOffsetMinutes: v.optional(v.number()) },
handler: async (ctx, { userId, tzOffsetMinutes = 0 }) => {
args: {
userId: v.id('users'),
tzOffsetMinutes: v.optional(v.number()),
timeZone: v.optional(v.string()),
},
handler: async (ctx, { userId, tzOffsetMinutes = 0, timeZone }) => {
const actor = await getOptionalUser(ctx);
if (!actor || actor.deletedAt !== undefined || actor._id === userId) return null;
const person = await ctx.db.get(userId);
if (!person || person.deletedAt !== undefined) return null;
const lowId = String(actor._id) < String(userId) ? actor._id : userId;
const highId = lowId === actor._id ? userId : actor._id;
const [friendship, conversation, actorGroups, personGroups, presence, settings] =
const [friendship, conversation, actorGroups, personGroups, presence, settings, actorSettings] =
await Promise.all([
ctx.db
.query('friendships')
Expand All @@ -459,6 +582,10 @@
.query('userSettings')
.withIndex('by_user', (q) => q.eq('userId', userId))
.unique(),
ctx.db
.query('userSettings')
.withIndex('by_user', (q) => q.eq('userId', actor._id))
.unique(),
]);
const viewerGroupIds = new Set(actorGroups.map((row) => String(row.groupId)));
const sharedGroupIds = personGroups
Expand All @@ -467,26 +594,36 @@
if (!friendship && !conversation && sharedGroupIds.length === 0) return null;

const now = Date.now();
const offset = tzOffsetMinutes * 60_000;
const todayStart = Math.floor((now - offset) / DAY_MS) * DAY_MS + offset;
const windowStart = todayStart - (ACTIVITY_DAYS - 1) * DAY_MS;
const days = Array.from({ length: ACTIVITY_DAYS }, (_, index) => ({
dayStart: windowStart + index * DAY_MS,
sent: 0,
received: 0,
}));
let validZone: string | undefined;
for (const candidate of [timeZone, actorSettings?.timezone, actor.timezone]) {
if (!candidate) continue;
try {
new Intl.DateTimeFormat('en-US', { timeZone: candidate });
validZone = candidate;
break;
} catch {
continue;
}
}
const { starts, endAt } = activityDayStarts(now, validZone, tzOffsetMinutes);
Comment on lines +597 to +608

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 Honor caller-provided timezone offsets

All existing web, mobile, and MCP callers provide tzOffsetMinutes, but authenticated users normally have userSettings.timezone, so this precedence always selects the stored zone and silently ignores the supplied offset. When the current device or requested MCP timezone differs from the saved profile zone, message buckets shift to different calendar days while UI date labels still use the device timezone; the MCP tool also violates its contract that the offset controls day buckets. Use the stored zone only when the caller supplies neither an IANA zone nor an offset, or update callers and renderers to use the selected zone consistently.

Useful? React with 👍 / 👎.

const windowStart = starts[0]!;
const days = starts.map((dayStart) => ({ dayStart, sent: 0, received: 0 }));
const mix = { text: 0, image: 0, audio: 0, ai: 0 };
let total = 0;
let totalMessagesCapped = false;
if (conversation) {
const recent = await ctx.db
.query('directMessages')
.withIndex('by_conversation_createdAt', (q) =>
q.eq('conversationId', conversation._id).gte('createdAt', windowStart),
q.eq('conversationId', conversation._id).gte('createdAt', windowStart).lt('createdAt', endAt),
)
.take(ACTIVITY_MESSAGE_LIMIT);
for (const message of recent) {
const index = Math.floor((message.createdAt - windowStart) / DAY_MS);
const day = days[index];
.order('desc')
.take(ACTIVITY_MESSAGE_LIMIT + 1);
totalMessagesCapped = recent.length > ACTIVITY_MESSAGE_LIMIT;
const includedMessages = Math.min(recent.length, ACTIVITY_MESSAGE_LIMIT);
for (let index = 0; index < includedMessages; index += 1) {
const message = recent[index]!;
const day = days[activityDayIndex(starts, message.createdAt)];
if (!day) continue;
if (message.senderId === actor._id && message.kind !== 'ai') day.sent += 1;
else day.received += 1;
Expand All @@ -512,6 +649,7 @@
lastSeenAt: (settings?.showLastSeen ?? true) ? (presence?.lastSeenAt ?? null) : null,
days,
totalMessages: total,
totalMessagesCapped,

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 Surface capped message totals to analytics consumers

For conversations with more than 2,000 messages in the 30-day window, the query now returns totalMessagesCapped: true and totalMessages: 2000, but none of the web, native, or profile analytics consumers include this new field in their data types or rendering; they continue displaying “2000 messages” as an exact result. Propagate the flag so capped totals and charts are identified as lower bounds, such as 2000+.

Useful? React with 👍 / 👎.

mix,
sharedGroups: groups.filter((group) => group !== null),
};
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/finance/native/PeopleAnalyticsScreens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ export function PersonAnalyticsScreen(p: PersonAnalyticsScreenProps) {
['Text', d.mix.text],
['Photos', d.mix.image],
['Voice', d.mix.audio],
['FinAI', d.mix.ai],
['FinAI replies', d.mix.ai],
] as const
).filter(([, value]) => value > 0);
return (
Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/finance/web/PeopleAnalyticsScreens.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ export function PersonAnalyticsScreen(p: PersonAnalyticsScreenProps) {
['text', 'Text', d.mix.text],
['image', 'Photos', d.mix.image],
['audio', 'Voice', d.mix.audio],
['ai', 'FinAI', d.mix.ai],
['ai', 'FinAI replies', d.mix.ai],
] as const
)
.filter(([, , value]) => value > 0)
Expand Down
Loading
Loading