xonecas.io
5414
Sa

sat / files

sat / src / app / actions / conversations.ts

2.5 KB
1"use server";
2
3import { desc, eq } from "drizzle-orm";
4import { revalidatePath } from "next/cache";
5import { db } from "@/db";
6import { conversations, type NewTurn, turns } from "@/db/schema";
7
8export async function getConversations() {
9  return db.query.conversations.findMany({
10    orderBy: [desc(conversations.updatedAt)],
11  });
12}
13
14export async function getConversation(id: string) {
15  return db.query.conversations.findFirst({
16    where: eq(conversations.id, id),
17    with: {
18      turns: {
19        orderBy: [turns.createdAt],
20      },
21    },
22  });
23}
24
25export async function createConversation() {
26  const [conversation] = await db
27    .insert(conversations)
28    .values({})
29    .returning({ id: conversations.id });
30
31  revalidatePath("/");
32  return conversation;
33}
34
35export async function addTurn(
36  conversationId: string,
37  data: Omit<NewTurn, "id" | "conversationId" | "createdAt">,
38) {
39  // Insert the turn
40  const [turn] = await db
41    .insert(turns)
42    .values({
43      conversationId,
44      ...data,
45    })
46    .returning();
47
48  // Check if this is the first user turn to set the title
49  if (data.role === "user") {
50    const conversation = await db.query.conversations.findFirst({
51      where: eq(conversations.id, conversationId),
52    });
53
54    if (conversation && !conversation.title) {
55      // Set title from first ~50 chars of user message
56      const title =
57        data.content.length > 50
58          ? `${data.content.slice(0, 47)}...`
59          : data.content;
60
61      await db
62        .update(conversations)
63        .set({ title, updatedAt: new Date() })
64        .where(eq(conversations.id, conversationId));
65    } else {
66      // Just update the timestamp
67      await db
68        .update(conversations)
69        .set({ updatedAt: new Date() })
70        .where(eq(conversations.id, conversationId));
71    }
72  } else {
73    // Update timestamp for assistant turns too
74    await db
75      .update(conversations)
76      .set({ updatedAt: new Date() })
77      .where(eq(conversations.id, conversationId));
78  }
79
80  revalidatePath("/");
81  revalidatePath(`/conversation/${conversationId}`);
82
83  return turn;
84}
85
86export async function deleteConversation(id: string) {
87  await db.delete(conversations).where(eq(conversations.id, id));
88  revalidatePath("/");
89}
90
91export async function updateConversationSummary(id: string, summary: string) {
92  await db
93    .update(conversations)
94    .set({ summary, updatedAt: new Date() })
95    .where(eq(conversations.id, id));
96}
97
98// Type for the full conversation with turns
99export type ConversationWithTurns = NonNullable<
100  Awaited<ReturnType<typeof getConversation>>
101>;