🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(channel): carry an Agent's rename into its direct conversations (#23134)
Arvin Xu8fc4fb1858a7
diff --git a/packages/database/src/models/agent/update.ts b/packages/database/src/models/agent/update.tsindex 39743372672..ddb816d743c 100644--- a/packages/database/src/models/agent/update.ts+++ b/packages/database/src/models/agent/update.ts@@ -8,6 +8,7 @@ import type { PartialDeep } from 'type-fest';import { merge } from '@/utils/merge';+import { writeAgent } from '../../repositories/channel/agentRename';import type { AgentItem } from '../../schemas';import { agents, sessionGroups } from '../../schemas';import { sanitizeAgentApiConfig } from '../../utils/sanitizeAgentApiConfig';@@ -132,10 +133,10 @@ export const update = async (ctx: AgentModelContext, agentId: string, data: Partconst sanitizedData = stripImmutableFields(apiSafeData);await assertNotAgentBuilderProtectedWrite(ctx, agentId, sanitizedData);- return ctx.db- .update(agents)- .set({ ...sanitizedData, updatedAt: new Date() })- .where(and(eq(agents.id, agentId), ctx.ownership()));+ return writeAgent(ctx.db, and(eq(agents.id, agentId), ctx.ownership()), agentId, {+ ...sanitizedData,+ updatedAt: new Date(),+ });};/**@@ -373,10 +374,7 @@ export const updateConfig = async () as Partial<typeof mergedValue>;if (!Object.values(updateData).some((value) => value !== undefined)) return;- return ctx.db- .update(agents)- .set(updateData)- .where(and(eq(agents.id, agentId), ctx.ownership()));+ return writeAgent(ctx.db, and(eq(agents.id, agentId), ctx.ownership()), agentId, updateData);};/**diff --git a/packages/database/src/repositories/channel/__tests__/agentRename.test.ts b/packages/database/src/repositories/channel/__tests__/agentRename.test.tsnew file mode 100644index 00000000000..464ad5dcfd0--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/agentRename.test.ts@@ -0,0 +1,111 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { AgentModel } from '../../../models/agent';+import { agents, channelMembers, channels } from '../../../schemas';+import { ChannelRepository } from '..';+import { writeAgent } from '../agentRename';+import { createChannelFixture } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-agent-rename');+beforeEach(fixture.setup);+afterEach(fixture.cleanup);++const createDirect = async (title: string) => {+ const [agent] = await db.insert(agents).values({ title, userId: fixture.ownerId }).returning();+ const { channel } = await new ChannelRepository(db, fixture.ownerId).create({+ agentConfig: {},+ agentId: agent.id,+ title,+ });+ return { agent, channel };+};++const titleOf = async (channelId: string) => {+ const [channel] = await db.select().from(channels).where(eq(channels.id, channelId));+ return channel.title;+};++const memberNameOf = async (channelId: string) => {+ const [member] = await db+ .select()+ .from(channelMembers)+ .where(and(eq(channelMembers.channelId, channelId), eq(channelMembers.actorType, 'agent')));+ return member.name;+};++describe('renaming an Agent', () => {+ it.each(['updateConfig', 'update'] as const)(+ 'renames its direct conversation and member label through %s',+ async (method) => {+ const { agent, channel } = await createDirect('Writer (Copy)');+ expect(await memberNameOf(channel.id)).toBe('Writer (Copy)');++ await new AgentModel(db, fixture.ownerId)[method](agent.id, { title: 'Writer' });++ expect(await titleOf(channel.id)).toBe('Writer');+ expect(await memberNameOf(channel.id)).toBe('Writer');+ },+ );++ it('follows the name that wins over the title', async () => {+ const { agent, channel } = await createDirect('Writer');++ await new AgentModel(db, fixture.ownerId).updateConfig(agent.id, { name: 'Ada' });++ expect(await titleOf(channel.id)).toBe('Ada');+ expect(await memberNameOf(channel.id)).toBe('Ada');+ });++ it('keeps a title or label a member set in the Channel', async () => {+ const { agent, channel } = await createDirect('Writer');+ await db.update(channels).set({ title: 'My writer' }).where(eq(channels.id, channel.id));+ await db+ .update(channelMembers)+ .set({ name: 'Scribe' })+ .where(eq(channelMembers.channelId, channel.id));++ await new AgentModel(db, fixture.ownerId).updateConfig(agent.id, { title: 'Editor' });++ expect(await titleOf(channel.id)).toBe('My writer');+ expect(await memberNameOf(channel.id)).toBe('Scribe');+ });++ it.each(['updateConfig', 'update'] as const)(+ 'ends on the name the Agent keeps when two renames through %s overlap',+ async (method) => {+ const { agent, channel } = await createDirect('Writer');+ const model = new AgentModel(db, fixture.ownerId);++ await Promise.all([+ model[method](agent.id, { title: 'Editor' }),+ model[method](agent.id, { title: 'Reviewer' }),+ ]);++ const [renamed] = await db.select().from(agents).where(eq(agents.id, agent.id));+ expect(await titleOf(channel.id)).toBe(renamed.title);+ expect(await memberNameOf(channel.id)).toBe(renamed.title);+ },+ );++ it('reruns a rename that PostgreSQL picked as a deadlock victim', async () => {+ const { agent, channel } = await createDirect('Writer');+ const deadlock = Object.assign(new Error('deadlock detected'), {+ cause: { code: '40P01' },+ });+ const transaction = vi+ .fn()+ .mockRejectedValueOnce(deadlock)+ .mockImplementation((fn) => db.transaction(fn));+ const flaky = Object.assign(Object.create(db), { transaction }) as typeof db;++ await writeAgent(flaky, eq(agents.id, agent.id), agent.id, { title: 'Editor' });++ expect(transaction).toHaveBeenCalledTimes(2);+ expect(await titleOf(channel.id)).toBe('Editor');+ expect(await memberNameOf(channel.id)).toBe('Editor');+ });+});diff --git a/packages/database/src/repositories/channel/agentRename.ts b/packages/database/src/repositories/channel/agentRename.tsnew file mode 100644index 00000000000..9910e850ed6--- /dev/null+++ b/packages/database/src/repositories/channel/agentRename.ts@@ -0,0 +1,126 @@+import { agentDisplayName, CHANNEL_LIMITS } from '@lobechat/types';+import type { SQL } from 'drizzle-orm';+import { and, asc, eq, inArray, or } from 'drizzle-orm';+import type { PgUpdateSetSource } from 'drizzle-orm/pg-core';++import { agents, channelMembers, channels } from '../../schemas';+import type { LobeChatDatabase, Transaction } from '../../type';+import { normalizeInboxAgentTitle } from '../../utils/inboxAgent';++/** PostgreSQL `deadlock_detected`: the victim's transaction was rolled back. */+const DEADLOCK_DETECTED = '40P01';+const RENAME_ATTEMPTS = 3;++/** The SQLSTATE of a driver error, which Drizzle may wrap in `cause`. */+const postgresErrorCode = (error: unknown): string | undefined => {+ let current = error;+ for (let depth = 0; depth < 5 && current && typeof current === 'object'; depth++) {+ const code = (current as Record<string, unknown>).code;+ if (typeof code === 'string') return code;+ current = (current as { cause?: unknown }).cause;+ }+};++interface AgentLabelFields {+ name?: string | null;+ slug?: string | null;+ title?: string | null;+}++/** The label a Channel stores for an Agent when it opens a direct conversation or adds it. */+const channelAgentLabel = (agent: AgentLabelFields) =>+ agentDisplayName(+ { name: agent.name, title: normalizeInboxAgentTitle(agent.title, agent) },+ 'Agent',+ );++/**+ * Carries an Agent's rename into the Channels that still show its old name. A direct+ * conversation's title and an Agent member's label are copied from the Agent when created, so+ * without this they keep the name it had then. Only copies that still equal the old name follow:+ * one a member renamed in the Channel stays as they set it.+ */+const followAgentRename = async (+ db: LobeChatDatabase | Transaction,+ agentId: string,+ before: AgentLabelFields,+ after: AgentLabelFields,+) => {+ const previous = channelAgentLabel(before);+ const next = channelAgentLabel(after);+ if (previous === next) return;++ const titleOf = (label: string) => label.slice(0, CHANNEL_LIMITS.titleLength);+ await db+ .update(channels)+ .set({ title: titleOf(next) })+ .where(and(eq(channels.agentId, agentId), eq(channels.title, titleOf(previous))));+ await db+ .update(channelMembers)+ .set({ name: next })+ .where(+ and(+ eq(channelMembers.agentId, agentId),+ eq(channelMembers.actorType, 'agent'),+ eq(channelMembers.name, previous),+ ),+ );+};++/**+ * Write an Agent's columns, `where` selecting its row in the caller's scope. A rename also+ * carries the new label into its Channels, under row locks: overlapping renames would otherwise+ * each read the same previous label, and the later one would match no copy, leaving them at the+ * earlier name for good.+ *+ * Channel writes lock the Channel before the Agent (adding a member holds the Agent `for share`+ * under the Channel lock), so a rename takes the Channels it touches first, in id order, and the+ * Agent last. Deleting the Agent locks it first and reaches its Channels through the cascade, so+ * no single order suits both; a rename that loses a deadlock reruns whole, re-reading the label,+ * and finds nothing to rename once the Agent is gone.+ */+export const writeAgent = async (+ db: LobeChatDatabase,+ where: SQL | undefined,+ agentId: string,+ data: AgentLabelFields & PgUpdateSetSource<typeof agents>,+) => {+ if (data.name === undefined && data.title === undefined)+ return db.update(agents).set(data).where(where);++ for (let attempt = 1; ; attempt++) {+ try {+ return await renameAgent(db, where, agentId, data);+ } catch (error) {+ if (postgresErrorCode(error) !== DEADLOCK_DETECTED || attempt === RENAME_ATTEMPTS)+ throw error;+ }+ }+};++const renameAgent = (+ db: LobeChatDatabase,+ where: SQL | undefined,+ agentId: string,+ data: AgentLabelFields & PgUpdateSetSource<typeof agents>,+) =>+ db.transaction(async (tx) => {+ const memberOf = tx+ .select({ id: channelMembers.channelId })+ .from(channelMembers)+ .where(and(eq(channelMembers.agentId, agentId), eq(channelMembers.actorType, 'agent')));+ await tx+ .select({ id: channels.id })+ .from(channels)+ .where(or(eq(channels.agentId, agentId), inArray(channels.id, memberOf)))+ .orderBy(asc(channels.id))+ .for('update');+ const [before] = await tx+ .select({ name: agents.name, slug: agents.slug, title: agents.title })+ .from(agents)+ .where(where)+ .for('update');+ const result = await tx.update(agents).set(data).where(where);+ if (before) await followAgentRename(tx, agentId, before, { ...before, ...data });+ return result;+ });