Skip to content

Commit 3646476

Browse files
committed
Fix user insertion conflicts and add message parts tracking
- Add onConflictDoNothing to user creation to handle race conditions - Fetch conflicted users that were prevented from insertion - Create part records for agent task messages to properly track content
1 parent 3baa98d commit 3646476

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

apps/interaction-worker/src/services/loop/store-loop-messages.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,11 +96,30 @@ export const storeLoopMessages = async (
9696
const newUsers = await db
9797
.insert(users)
9898
.values(missingUsers.map((phoneNumber) => ({ phoneNumber })))
99+
.onConflictDoNothing({ target: users.phoneNumber })
99100
.returning();
100101

101102
newUsers.forEach((user) => {
102103
userMap.set(user.phoneNumber, user.id);
103104
});
105+
106+
// If onConflictDoNothing prevented some inserts, fetch those users
107+
if (newUsers.length < missingUsers.length) {
108+
const stillMissingPhones = missingUsers.filter(
109+
(phone) => !userMap.has(phone),
110+
);
111+
if (stillMissingPhones.length > 0) {
112+
const conflictedUsers = await db
113+
.select()
114+
.from(users)
115+
.where(inArray(users.phoneNumber, stillMissingPhones));
116+
117+
conflictedUsers.forEach((user) => {
118+
userMap.set(user.phoneNumber, user.id);
119+
});
120+
}
121+
}
122+
104123
logger.info("Created new users", {
105124
count: newUsers.length,
106125
phoneNumbers: missingUsers,

apps/interaction-worker/src/tools/send-message-to-agent.ts

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { Agent, getDb } from "@poppy/db";
2-
import { messages as messagesTable } from "@poppy/db";
2+
import { messages as messagesTable, parts } from "@poppy/db";
33
import { logger } from "@poppy/hono-helpers";
44
import { generateId, tool } from "ai";
55
import { z } from "zod";
@@ -101,8 +101,9 @@ The agent has tools for a wide variety of tasks. Use this tool often.
101101
});
102102

103103
// Record the message in the messages table
104+
const taskMessageId = generateId();
104105
await db.insert(messagesTable).values({
105-
id: generateId(),
106+
id: taskMessageId,
106107
conversationId,
107108
fromAgentId: interactionAgentId,
108109
toAgentId: executionAgent.id,
@@ -114,6 +115,18 @@ The agent has tools for a wide variety of tasks. Use this tool often.
114115
},
115116
});
116117

118+
// Create part record for the message content
119+
await db.insert(parts).values({
120+
id: generateId(),
121+
messageId: taskMessageId,
122+
type: "text",
123+
content: {
124+
type: "text",
125+
text: message,
126+
},
127+
order: 0,
128+
});
129+
117130
// Call execution-worker via RPC to execute the task
118131
logger
119132
.withTags({

0 commit comments

Comments
 (0)