-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmessage_queries.ts
More file actions
157 lines (143 loc) · 4.46 KB
/
Copy pathmessage_queries.ts
File metadata and controls
157 lines (143 loc) · 4.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import type { Id } from "./_generated/dataModel";
import { assertOwnsChat } from "./chats";
import { query } from "./_generated/server";
import { v } from "convex/values";
import { requireAuthUserId } from "./lib/auth";
import { messageDoc } from "./message_validators";
import { getVerifiedStorageIds } from "./message_helpers";
export const list = query({
args: {
chatId: v.id("chats"),
userId: v.id("users"),
},
returns: v.array(messageDoc),
handler: async (ctx, args) => {
const userId = await requireAuthUserId(ctx, args.userId);
const chat = await assertOwnsChat(ctx, args.chatId, userId);
if (!chat) return [];
const messages = await ctx.db
.query("messages")
.withIndex("by_chat_not_deleted", (q) =>
q.eq("chatId", args.chatId).eq("deletedAt", undefined)
)
.order("asc")
.collect();
const allStorageIds: Id<"_storage">[] = [];
for (const message of messages) {
if (message.attachments) {
for (const attachment of message.attachments) {
allStorageIds.push(attachment.storageId);
}
}
}
let urlMap = new Map<Id<"_storage">, string | null>();
if (allStorageIds.length > 0) {
const uniqueStorageIds = Array.from(new Set(allStorageIds));
const verifiedIds = await getVerifiedStorageIds(ctx, uniqueStorageIds, userId);
const urlPromises = uniqueStorageIds.map(async (storageId) => {
if (!verifiedIds.has(storageId)) {
return { storageId, url: null };
}
try {
const url = await ctx.storage.getUrl(storageId);
return { storageId, url };
} catch {
return { storageId, url: null };
}
});
const urlResults = await Promise.all(urlPromises);
for (const { storageId, url } of urlResults) {
urlMap.set(storageId, url);
}
}
const messagesWithUrls = messages.map((message) => {
if (!message.attachments || message.attachments.length === 0) {
return message;
}
return {
...message,
attachments: message.attachments.map((attachment) => ({
...attachment,
url: urlMap.get(attachment.storageId) ?? undefined,
})),
};
});
return messagesWithUrls.map((msg) => ({
_id: msg._id,
clientMessageId: msg.clientMessageId,
role: msg.role,
content: msg.content,
modelId: msg.modelId,
provider: msg.provider,
reasoningEffort: msg.reasoningEffort,
webSearchEnabled: msg.webSearchEnabled,
webSearchUsed: msg.webSearchUsed,
webSearchCallCount: msg.webSearchCallCount,
toolCallCount: msg.toolCallCount,
maxSteps: msg.maxSteps,
reasoning: msg.reasoning,
thinkingTimeMs: msg.thinkingTimeMs,
thinkingTimeSec: msg.thinkingTimeSec,
reasoningCharCount: msg.reasoningCharCount,
reasoningChunkCount: msg.reasoningChunkCount,
reasoningTokenCount: msg.reasoningTokenCount,
reasoningRequested: msg.reasoningRequested,
toolInvocations: msg.toolInvocations,
chainOfThoughtParts: msg.chainOfThoughtParts,
status: msg.status,
streamId: msg.streamId,
attachments: msg.attachments,
error: msg.error,
messageType: msg.messageType,
createdAt: msg.createdAt,
deletedAt: msg.deletedAt,
tokenUsage: msg.tokenUsage,
tokensPerSecond: msg.tokensPerSecond,
timeToFirstTokenMs: msg.timeToFirstTokenMs,
totalDurationMs: msg.totalDurationMs,
compareGroup: msg.compareGroup,
}));
},
});
export const getFirstUserMessage = query({
args: {
chatId: v.id("chats"),
userId: v.id("users"),
},
returns: v.union(v.string(), v.null()),
handler: async (ctx, args) => {
const userId = await requireAuthUserId(ctx, args.userId);
const chat = await assertOwnsChat(ctx, args.chatId, userId);
if (!chat) return null;
const message = await ctx.db
.query("messages")
.withIndex("by_chat_not_deleted", (q) =>
q.eq("chatId", args.chatId).eq("deletedAt", undefined)
)
.filter((q) => q.eq(q.field("role"), "user"))
.order("asc")
.first();
return message?.content ?? null;
},
});
export const getActiveStream = query({
args: {
chatId: v.id("chats"),
userId: v.id("users"),
},
returns: v.union(v.string(), v.null()),
handler: async (ctx, args) => {
const userId = await requireAuthUserId(ctx, args.userId);
const chat = await assertOwnsChat(ctx, args.chatId, userId);
if (!chat) return null;
const streamingMessage = await ctx.db
.query("messages")
.withIndex("by_chat_not_deleted", (q) =>
q.eq("chatId", args.chatId).eq("deletedAt", undefined)
)
.order("desc")
.filter((q) => q.eq(q.field("status"), "streaming"))
.first();
return streamingMessage?.streamId ?? null;
},
});