|
| 1 | +import { v } from "convex/values"; |
| 2 | +import type { Id } from "./_generated/dataModel"; |
| 3 | +import type { MutationCtx, QueryCtx } from "./_generated/server"; |
| 4 | +import { mutation, query } from "./_generated/server"; |
| 5 | +import { assertOwnsChat } from "./chats"; |
| 6 | +import { requireAuthUserId } from "./lib/auth"; |
| 7 | + |
| 8 | +const shareDoc = v.object({ |
| 9 | + _id: v.id("chatShares"), |
| 10 | + _creationTime: v.number(), |
| 11 | + userId: v.id("users"), |
| 12 | + chatId: v.id("chats"), |
| 13 | + shareId: v.string(), |
| 14 | + createdAt: v.number(), |
| 15 | + updatedAt: v.number(), |
| 16 | + revokedAt: v.optional(v.number()), |
| 17 | +}); |
| 18 | + |
| 19 | +const sharedMessageDoc = v.object({ |
| 20 | + id: v.string(), |
| 21 | + role: v.string(), |
| 22 | + content: v.string(), |
| 23 | + createdAt: v.number(), |
| 24 | +}); |
| 25 | + |
| 26 | +const sharedPreviewDoc = v.object({ |
| 27 | + shareId: v.string(), |
| 28 | + title: v.string(), |
| 29 | + firstUserPrompt: v.union(v.string(), v.null()), |
| 30 | + firstAssistantResponse: v.union(v.string(), v.null()), |
| 31 | +}); |
| 32 | + |
| 33 | +const sharedChatDoc = v.object({ |
| 34 | + shareId: v.string(), |
| 35 | + title: v.string(), |
| 36 | + firstUserPrompt: v.union(v.string(), v.null()), |
| 37 | + firstAssistantResponse: v.union(v.string(), v.null()), |
| 38 | + messages: v.array(sharedMessageDoc), |
| 39 | +}); |
| 40 | + |
| 41 | +const MAX_PUBLIC_MESSAGES = 300; |
| 42 | + |
| 43 | +function makeShareId() { |
| 44 | + const token = crypto.randomUUID().replaceAll("-", ""); |
| 45 | + return token.slice(0, 22); |
| 46 | +} |
| 47 | + |
| 48 | +async function generateUniqueShareId(ctx: MutationCtx): Promise<string> { |
| 49 | + for (let i = 0; i < 5; i++) { |
| 50 | + const shareId = makeShareId(); |
| 51 | + const existing = await ctx.db |
| 52 | + .query("chatShares") |
| 53 | + .withIndex("by_share_id", (q) => q.eq("shareId", shareId)) |
| 54 | + .first(); |
| 55 | + if (!existing) return shareId; |
| 56 | + } |
| 57 | + throw new Error("Unable to generate share token"); |
| 58 | +} |
| 59 | + |
| 60 | +async function getActiveShareForChat( |
| 61 | + ctx: QueryCtx | MutationCtx, |
| 62 | + userId: Id<"users">, |
| 63 | + chatId: Id<"chats">, |
| 64 | +) { |
| 65 | + return ctx.db |
| 66 | + .query("chatShares") |
| 67 | + .withIndex("by_user_chat_revoked_updated", (q) => |
| 68 | + q.eq("userId", userId).eq("chatId", chatId).eq("revokedAt", undefined), |
| 69 | + ) |
| 70 | + .order("desc") |
| 71 | + .first(); |
| 72 | +} |
| 73 | + |
| 74 | +function normalizePreviewText(text: string) { |
| 75 | + return text.replace(/\s+/g, " ").trim(); |
| 76 | +} |
| 77 | + |
| 78 | +function buildPreview(messages: Array<{ role: string; content: string }>) { |
| 79 | + let firstUserPrompt: string | null = null; |
| 80 | + let firstAssistantResponse: string | null = null; |
| 81 | + |
| 82 | + for (const message of messages) { |
| 83 | + const content = normalizePreviewText(message.content); |
| 84 | + if (!content) continue; |
| 85 | + if (!firstUserPrompt && message.role === "user") { |
| 86 | + firstUserPrompt = content; |
| 87 | + continue; |
| 88 | + } |
| 89 | + if (!firstAssistantResponse && message.role === "assistant") { |
| 90 | + firstAssistantResponse = content; |
| 91 | + } |
| 92 | + if (firstUserPrompt && firstAssistantResponse) break; |
| 93 | + } |
| 94 | + |
| 95 | + return { firstUserPrompt, firstAssistantResponse }; |
| 96 | +} |
| 97 | + |
| 98 | +export const getByChat = query({ |
| 99 | + args: { |
| 100 | + chatId: v.id("chats"), |
| 101 | + userId: v.id("users"), |
| 102 | + }, |
| 103 | + returns: v.union(shareDoc, v.null()), |
| 104 | + handler: async (ctx, args) => { |
| 105 | + const userId = await requireAuthUserId(ctx, args.userId); |
| 106 | + const chat = await assertOwnsChat(ctx, args.chatId, userId); |
| 107 | + if (!chat) return null; |
| 108 | + return getActiveShareForChat(ctx, userId, args.chatId); |
| 109 | + }, |
| 110 | +}); |
| 111 | + |
| 112 | +export const createOrGet = mutation({ |
| 113 | + args: { |
| 114 | + chatId: v.id("chats"), |
| 115 | + userId: v.id("users"), |
| 116 | + }, |
| 117 | + returns: v.object({ |
| 118 | + shareId: v.string(), |
| 119 | + createdAt: v.number(), |
| 120 | + }), |
| 121 | + handler: async (ctx, args) => { |
| 122 | + const userId = await requireAuthUserId(ctx, args.userId); |
| 123 | + const chat = await assertOwnsChat(ctx, args.chatId, userId); |
| 124 | + if (!chat) { |
| 125 | + throw new Error("Chat not found"); |
| 126 | + } |
| 127 | + |
| 128 | + const existing = await getActiveShareForChat(ctx, userId, args.chatId); |
| 129 | + if (existing) { |
| 130 | + return { |
| 131 | + shareId: existing.shareId, |
| 132 | + createdAt: existing.createdAt, |
| 133 | + }; |
| 134 | + } |
| 135 | + |
| 136 | + const now = Date.now(); |
| 137 | + const shareId = await generateUniqueShareId(ctx); |
| 138 | + |
| 139 | + await ctx.db.insert("chatShares", { |
| 140 | + userId, |
| 141 | + chatId: args.chatId, |
| 142 | + shareId, |
| 143 | + createdAt: now, |
| 144 | + updatedAt: now, |
| 145 | + }); |
| 146 | + |
| 147 | + return { |
| 148 | + shareId, |
| 149 | + createdAt: now, |
| 150 | + }; |
| 151 | + }, |
| 152 | +}); |
| 153 | + |
| 154 | +export const revoke = mutation({ |
| 155 | + args: { |
| 156 | + chatId: v.id("chats"), |
| 157 | + userId: v.id("users"), |
| 158 | + }, |
| 159 | + returns: v.object({ revoked: v.boolean() }), |
| 160 | + handler: async (ctx, args) => { |
| 161 | + const userId = await requireAuthUserId(ctx, args.userId); |
| 162 | + const chat = await assertOwnsChat(ctx, args.chatId, userId); |
| 163 | + if (!chat) return { revoked: false }; |
| 164 | + |
| 165 | + const share = await getActiveShareForChat(ctx, userId, args.chatId); |
| 166 | + if (!share) return { revoked: false }; |
| 167 | + |
| 168 | + const now = Date.now(); |
| 169 | + await ctx.db.patch(share._id, { |
| 170 | + revokedAt: now, |
| 171 | + updatedAt: now, |
| 172 | + }); |
| 173 | + |
| 174 | + return { revoked: true }; |
| 175 | + }, |
| 176 | +}); |
| 177 | + |
| 178 | +export const getPreviewByShareId = query({ |
| 179 | + args: { |
| 180 | + shareId: v.string(), |
| 181 | + }, |
| 182 | + returns: v.union(sharedPreviewDoc, v.null()), |
| 183 | + handler: async (ctx, args) => { |
| 184 | + const share = await ctx.db |
| 185 | + .query("chatShares") |
| 186 | + .withIndex("by_share_id", (q) => q.eq("shareId", args.shareId)) |
| 187 | + .first(); |
| 188 | + if (!share || share.revokedAt) return null; |
| 189 | + |
| 190 | + const chat = await ctx.db.get(share.chatId); |
| 191 | + if (!chat || chat.deletedAt) return null; |
| 192 | + |
| 193 | + const messagesPage = await ctx.db |
| 194 | + .query("messages") |
| 195 | + .withIndex("by_chat_not_deleted", (q) => |
| 196 | + q.eq("chatId", chat._id).eq("deletedAt", undefined), |
| 197 | + ) |
| 198 | + .order("asc") |
| 199 | + .paginate({ cursor: null, numItems: MAX_PUBLIC_MESSAGES }); |
| 200 | + |
| 201 | + const messages = messagesPage.page |
| 202 | + .filter((message) => message.role === "user" || message.role === "assistant") |
| 203 | + .map((message) => ({ |
| 204 | + role: message.role, |
| 205 | + content: message.content, |
| 206 | + })); |
| 207 | + const preview = buildPreview(messages); |
| 208 | + |
| 209 | + return { |
| 210 | + shareId: share.shareId, |
| 211 | + title: chat.title, |
| 212 | + firstUserPrompt: preview.firstUserPrompt, |
| 213 | + firstAssistantResponse: preview.firstAssistantResponse, |
| 214 | + }; |
| 215 | + }, |
| 216 | +}); |
| 217 | + |
| 218 | +export const getPublicByShareId = query({ |
| 219 | + args: { |
| 220 | + shareId: v.string(), |
| 221 | + }, |
| 222 | + returns: v.union(sharedChatDoc, v.null()), |
| 223 | + handler: async (ctx, args) => { |
| 224 | + const share = await ctx.db |
| 225 | + .query("chatShares") |
| 226 | + .withIndex("by_share_id", (q) => q.eq("shareId", args.shareId)) |
| 227 | + .first(); |
| 228 | + if (!share || share.revokedAt) return null; |
| 229 | + |
| 230 | + const chat = await ctx.db.get(share.chatId); |
| 231 | + if (!chat || chat.deletedAt) return null; |
| 232 | + |
| 233 | + const messagesPage = await ctx.db |
| 234 | + .query("messages") |
| 235 | + .withIndex("by_chat_not_deleted", (q) => |
| 236 | + q.eq("chatId", chat._id).eq("deletedAt", undefined), |
| 237 | + ) |
| 238 | + .order("asc") |
| 239 | + .paginate({ cursor: null, numItems: MAX_PUBLIC_MESSAGES }); |
| 240 | + |
| 241 | + const messages = messagesPage.page |
| 242 | + .filter((message) => message.role === "user" || message.role === "assistant") |
| 243 | + .map((message) => ({ |
| 244 | + id: message._id, |
| 245 | + role: message.role, |
| 246 | + content: message.content, |
| 247 | + createdAt: message.createdAt, |
| 248 | + })); |
| 249 | + const preview = buildPreview(messages); |
| 250 | + |
| 251 | + return { |
| 252 | + shareId: share.shareId, |
| 253 | + title: chat.title, |
| 254 | + firstUserPrompt: preview.firstUserPrompt, |
| 255 | + firstAssistantResponse: preview.firstAssistantResponse, |
| 256 | + messages, |
| 257 | + }; |
| 258 | + }, |
| 259 | +}); |
0 commit comments