Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(db): keep copied tool calls linked to their result messages (#20654)

Neko44c3a146b53b
diff --git a/packages/database/src/utils/copyMessagesInDatabase.test.ts b/packages/database/src/utils/copyMessagesInDatabase.test.ts
index 965d4084d45..6eaae41739a 100644
--- a/packages/database/src/utils/copyMessagesInDatabase.test.ts
+++ b/packages/database/src/utils/copyMessagesInDatabase.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { sql } from 'drizzle-orm';
+import { eq, sql } from 'drizzle-orm';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../core/getTestDB';
@@ -457,3 +457,109 @@ describe('copyMessagesInDatabase', () => {
expect(copied.map((m) => m.content).sort()).toEqual(['a', 'b']);
});
});
+
+/** @example Copied edit history keeps assistant tool calls linked to separate result rows. */
+describe('copied tool result identity', () => {
+ /** @example A legacy tool row can own its call even when it has a conversation parent. */
+ it('keeps a same-row tool call linked when its parent owns a different call', async () => {
+ // ROOT CAUSE:
+ // Choosing every tool row's parent as its call owner broke legacy same-row tools/plugins.
+ // Only a copied parent containing the matching call can supply the new call-ID seed.
+ await serverDB.insert(messages).values([
+ {
+ id: 'legacy-parent',
+ role: 'assistant',
+ content: '',
+ tools: [{ id: 'other-call' }],
+ topicId: sourceTopicId,
+ userId,
+ },
+ {
+ id: 'legacy-result',
+ role: 'tool',
+ content: 'legacy output',
+ parentId: 'legacy-parent',
+ tools: [{ id: 'legacy-call' }],
+ topicId: sourceTopicId,
+ userId,
+ },
+ ]);
+ await serverDB
+ .insert(messagePlugins)
+ .values({ id: 'legacy-result', toolCallId: 'legacy-call', userId });
+ await runCopy([
+ ['legacy-parent', 'copied-legacy-parent'],
+ ['legacy-result', 'copied-legacy-result'],
+ ]);
+ const [result] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'copied-legacy-result'));
+ const [plugin] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, result.id));
+ /** @example The copied plugin links to the same copied message's tool call. */
+ expect(result.tools?.[0]).toMatchObject({ id: plugin.toolCallId });
+ /** @example Copying still gives the call an independent identity. */
+ expect(plugin.toolCallId).not.toBe('legacy-call');
+ });
+
+ /** @example Real tool results are separate messages, not plugins on the assistant row. */
+ it('remaps both ends of a tool call and its result message together', async () => {
+ await serverDB.insert(messages).values([
+ {
+ id: 'tool-assistant',
+ role: 'assistant',
+ content: '',
+ topicId: sourceTopicId,
+ userId,
+ tools: [{ id: 'call-original', result_msg_id: 'tool-result', type: 'builtin' }],
+ },
+ {
+ id: 'tool-result',
+ role: 'tool',
+ content: 'TOOL-647-ONE',
+ parentId: 'tool-assistant',
+ topicId: sourceTopicId,
+ userId,
+ },
+ ]);
+ await serverDB.insert(messagePlugins).values({
+ id: 'tool-result',
+ apiName: 'shell',
+ arguments: '{}',
+ toolCallId: 'call-original',
+ userId,
+ });
+ // ROOT CAUSE:
+ // The old copy seeded the assistant call id with the new assistant id,
+ // but seeded the result's toolCallId with the new result id. It also left
+ // result_msg_id pointing into the source topic. Real history could not join.
+ await runCopy([
+ ['tool-assistant', 'copied-assistant'],
+ ['tool-result', 'copied-result'],
+ ]);
+ const [assistant] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'copied-assistant'));
+ const [result] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, 'copied-result'));
+ const tool = assistant.tools?.[0];
+ /** @example The result references the copied assistant's tool call. */
+ expect(tool).toMatchObject({ id: result.toolCallId, result_msg_id: 'copied-result' });
+ /** @example The copy receives its own tool identity. */
+ expect(result.toolCallId).not.toBe('call-original');
+ const [source] = await serverDB
+ .select()
+ .from(messages)
+ .where(eq(messages.id, 'tool-assistant'));
+ /** @example Source tool identifiers and result references remain unchanged. */
+ expect(source.tools).toEqual([
+ { id: 'call-original', result_msg_id: 'tool-result', type: 'builtin' },
+ ]);
+ });
+});
diff --git a/packages/database/src/utils/copyMessagesInDatabase.ts b/packages/database/src/utils/copyMessagesInDatabase.ts
index 31a1d73da93..2d87a561284 100644
--- a/packages/database/src/utils/copyMessagesInDatabase.ts
+++ b/packages/database/src/utils/copyMessagesInDatabase.ts
@@ -110,9 +110,9 @@ const seedIdMapTable = async (
};
/**
- * Deterministic per-message remap for tool-call ids: the same expression is
- * used for `messages.tools[].id` and `message_plugins.tool_call_id`, so a
- * message and its plugin rows stay linked without materializing a map.
+ * Deterministic per-assistant remap for tool-call ids. Both a call and its
+ * separate result row use the copied assistant id, so their identities agree
+ * without materializing tool payloads outside the database.
*/
const remappedToolId = (newMessageIdExpr: SQL, sourceToolIdExpr: SQL) =>
sql`'toolu_' || substr(md5(${newMessageIdExpr} || ${sourceToolIdExpr}), 1, 24)`;
@@ -129,6 +129,18 @@ const buildCopyColumns = (table: PgTable, overrides: Record<string, SQL | undefi
return { exprs: sql.join(exprs, sql`, `), names: sql.join(names, sql`, `) };
};
+/**
+ * Copies an authorized message graph and its dependent rows inside a transaction.
+ *
+ * Use when:
+ * - Creating an independent topic from selected historical messages.
+ *
+ * Expects:
+ * - An open transaction and explicit, authorized source-to-target identity maps.
+ *
+ * Returns:
+ * - Copied rows with remapped graph and tool references; source rows remain unchanged.
+ */
export const copyMessagesInDatabase = async ({
agentIdExpr,
agentIdPairs,
@@ -193,6 +205,12 @@ export const copyMessagesInDatabase = async ({
case
when jsonb_typeof(_tool.elem) = 'object' and jsonb_typeof(_tool.elem -> 'id') = 'string'
then jsonb_set(_tool.elem, '{id}', to_jsonb(${remappedToolId(newMessageId, sql`(_tool.elem ->> 'id')`)}))
+ || case when _tool.elem ? 'result_msg_id'
+ then jsonb_build_object('result_msg_id', (
+ select _result.new_id from _copy_msg_id_map _result
+ where _result.source_id = _tool.elem ->> 'result_msg_id'
+ ))
+ else '{}'::jsonb end
else _tool.elem
end
order by _tool.ord)
@@ -279,7 +297,19 @@ export const copyMessagesInDatabase = async ({
identifier: sql`left(${messagePlugins.identifier}, ${MAX_TOOL_IDENTIFIER_LENGTH})`,
toolCallId: sql`case
when ${messagePlugins.toolCallId} is null then null
- else ${remappedToolId(newMessageId, sql`${messagePlugins.toolCallId}`)}
+ else ${remappedToolId(
+ // A separate result borrows its parent's seed only when that parent owns the call.
+ // Legacy same-row calls/plugins retain their own seed, regardless of parent role.
+ sql`coalesce((
+ select _assistant.new_id from ${messages} _result
+ join _copy_msg_id_map _assistant on _assistant.source_id = _result.parent_id
+ join ${messages} _owner on _owner.id = _assistant.source_id
+ where _result.id = ${messagePlugins.id} and _result.role = 'tool'
+ and _owner.tools @> jsonb_build_array(jsonb_build_object('id', ${messagePlugins.toolCallId}))
+ and not coalesce(_result.tools @> jsonb_build_array(jsonb_build_object('id', ${messagePlugins.toolCallId})), false)
+ ), ${newMessageId})`,
+ sql`${messagePlugins.toolCallId}`,
+ )}
end`,
});