You need to create a function that paginates a user's chat room list, ordered by the most recent message, using QueryStream. A key consideration is how to effectively implement this "most recent" ordering.
chatRooms: defineTable({
type: v.union(v.literal("direct"), v.literal("group"), v.literal("ai")),
name: v.optional(v.string()),
lastMessageId: v.optional(v.id("chatMessages")),
isPublic: v.optional(v.boolean()),
updatedTime: v.number(),
})
.index("by_type_participants", ["type", "participants"])
.index("by_type_ownerId_aiId_updatedTime", ["type", "ownerId", "aiId", "updatedTime"]),
chatMembers: defineTable({
roomId: v.id("chatRooms"),
participantId: v.id("profiles"),
role: v.union(v.literal("admin"), v.literal("moderator"), v.literal("member"), v.literal("ai")),
joinTime: v.number(),
lastReadTime: v.number(),
isLeft: v.boolean(),
})
.index("by_participantId", ["participantId"])
.index("by_roomId_participantId", ["roomId", "participantId"])
.index("by_roomId_isLeft_lastReadTime", ["roomId", "isLeft", "lastReadTime"]),
chatMessages: defineTable({
roomId: v.id("chatRooms"),
senderId: v.id("profiles"),
role: v.union(v.literal("user"), v.literal("assistant"), v.literal("system"), v.literal("tool")),
content: v.optional(MESSAGE_CONTENT),
systemEventId: v.optional(v.id("chatSystemEvents")),
sentTime: v.number(),
})
.index("by_roomId_sentTime", ["roomId", "sentTime"])
.index("by_replyTo", ["replyTo"]),