🤯 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
✨ feat(channel): let a person edit the text of their own message (#23155)
Arvin Xu91b594b878e5
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex ab9da083477..e67fae561a7 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -267,6 +267,18 @@ export const channelRouter = router({await ctx.channelService.remove(input.channelId);return { success: true };}),+ editMessage: channelProcedure+ .input(+ z.object({+ channelId,+ content: z.string().max(CHANNEL_LIMITS.contentLength),+ messageId: z.uuid(),+ }),+ )+ .mutation(async ({ ctx, input }) => ({+ data: await ctx.channelService.editMessage(input.channelId, input.messageId, input.content),+ success: true,+ })),rename: channelProcedure.input(z.object({ channelId, title: z.string().trim().min(1).max(CHANNEL_LIMITS.titleLength) })).mutation(async ({ ctx, input }) => ({diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.tsindex 3378d373f58..1b3ffe4b0fc 100644--- a/apps/server/src/services/channel/ChannelService.ts+++ b/apps/server/src/services/channel/ChannelService.ts@@ -330,6 +330,12 @@ export class ChannelService {return channel;};+ editMessage = async (channelId: string, messageId: string, content: string) => {+ const message = await this.repository.editMessage(channelId, messageId, content);+ await this.changed(channelId);+ return message;+ };+addUser = async (channelId: string, userId: string) => {const member = await this.repository.addUser(channelId, userId);await this.changed(channelId);diff --git a/packages/database/src/repositories/channel/__tests__/editMessage.test.ts b/packages/database/src/repositories/channel/__tests__/editMessage.test.tsnew file mode 100644index 00000000000..3553f02046a--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/editMessage.test.ts@@ -0,0 +1,72 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { workspaceMembers } from '../../../schemas';+import { ChannelRepository } from '..';+import { createChannelFixture } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-edit-message');+beforeEach(async () => {+ await fixture.setup();+ await db.insert(workspaceMembers).values([+ { workspaceId: fixture.workspaceId, userId: fixture.ownerId, role: 'owner' },+ { workspaceId: fixture.workspaceId, userId: fixture.memberId },+ ]);+});+afterEach(fixture.cleanup);++const setup = async () => {+ const owner = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ const { channel } = await owner.create({ title: 'Edits' });+ await owner.addUser(channel.id, fixture.memberId);+ const member = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ const sent = await owner.send(channel.id, {+ content: 'Helo',+ requestKey: 'typo',+ routing: 'fallback',+ });+ return { channel, member, owner, sent };+};++describe('ChannelRepository.editMessage', () => {+ it('rewrites the author’s own text and marks it edited for every member', async () => {+ const { channel, member, owner, sent } = await setup();+ expect((await owner.detail(channel.id)).messages[0].editedAt).toBeNull();++ const edited = await owner.editMessage(channel.id, sent.id, ' Hello ');+ expect(edited).toMatchObject({ content: 'Hello', id: sent.id });+ expect(edited.editedAt).toBeInstanceOf(Date);++ const [seen] = (await member.detail(channel.id)).messages;+ expect(seen).toMatchObject({ content: 'Hello', mentions: sent.mentions });+ expect(seen.editedAt).toEqual(edited.editedAt);+ });++ it('leaves an unchanged message unmarked', async () => {+ const { channel, owner, sent } = await setup();+ expect((await owner.editMessage(channel.id, sent.id, 'Helo')).editedAt).toBeNull();+ expect((await owner.detail(channel.id)).messages[0].editedAt).toBeNull();+ });++ it('refuses someone else’s message, even for an admin', async () => {+ const { channel, owner } = await setup();+ const member = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ const theirs = await member.send(channel.id, {+ content: 'Mine',+ requestKey: 'member',+ routing: 'fallback',+ });+ await expect(owner.editMessage(channel.id, theirs.id, 'Changed')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ });++ it('refuses clearing the text of a message with no attachments', async () => {+ const { channel, owner, sent } = await setup();+ await expect(owner.editMessage(channel.id, sent.id, ' ')).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });+});diff --git a/packages/database/src/repositories/channel/edit.ts b/packages/database/src/repositories/channel/edit.tsnew file mode 100644index 00000000000..1545482bbbd--- /dev/null+++ b/packages/database/src/repositories/channel/edit.ts@@ -0,0 +1,54 @@+import { channelMessageEditedAt } from '@lobechat/types';+import { and, count, eq } from 'drizzle-orm';++import { channelMessageFiles, channelMessages } from '../../schemas';+import type { Transaction } from '../../type';+import { assertThreadOpen, findThread } from './delivery';+import { ChannelError } from './error';+import { audit } from './transaction';++/**+ * Rewrites the text of a person's own message. Its mentions and routing stay as they were sent:+ * an edit corrects what members read and what later replies see as context, it does not ask+ * anyone again. The time of the latest edit is kept in `metadata.editedAt`.+ */+export const editMessage = async (+ tx: Transaction,+ channelId: string,+ userId: string,+ messageId: string,+ content: string,+): Promise<{ content: string; editedAt: Date | null; id: string }> => {+ const [message] = await tx+ .select()+ .from(channelMessages)+ .where(and(eq(channelMessages.channelId, channelId), eq(channelMessages.id, messageId)));+ if (!message) throw new ChannelError('NOT_FOUND', 'Message not found');+ // Agent replies have no userId, so this also keeps them read-only.+ if (message.routingStatus === 'reply' || message.userId !== userId)+ throw new ChannelError('FORBIDDEN', 'Only the author can edit a message');+ assertThreadOpen(await findThread(tx, channelId, message.threadId));++ const next = content.trim();+ if (next === message.content)+ return { content: next, editedAt: channelMessageEditedAt(message.metadata), id: messageId };+ if (!next) {+ // Like sending, a message may be only attachments; one without them needs text.+ const [{ files }] = await tx+ .select({ files: count() })+ .from(channelMessageFiles)+ .where(eq(channelMessageFiles.messageId, messageId));+ if (!files) throw new ChannelError('BAD_REQUEST', 'A message needs text or attachments');+ }++ const editedAt = new Date();+ await tx+ .update(channelMessages)+ .set({+ content: next,+ metadata: { ...message.metadata, editedAt: editedAt.toISOString() },+ })+ .where(eq(channelMessages.id, messageId));+ await audit(tx, channelId, 'message_edited', messageId);+ return { content: next, editedAt, id: messageId };+};diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex b89090d0966..ea2f3986614 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -33,6 +33,7 @@ import {} from './agent';import { channelAvatarMembers } from './avatars';import { findThread } from './delivery';+import { editMessage } from './edit';import { ChannelError } from './error';import { lockPeerPair, peerOf, requireMutualContacts } from './peer';import {@@ -1101,6 +1102,10 @@ export class ChannelRepository {{ minRole: 'admin' },);+ /** Rewrites the text of the caller's own message; see `editMessage`. */+ editMessage = async (channelId: string, messageId: string, content: string) =>+ this.write(channelId, (tx) => editMessage(tx, channelId, this.userId, messageId, content));+/** Sends an unassigned message back to the decision model. Its author or an admin may retry. */retryRouting = async (channelId: string, messageId: string): Promise<ChannelMessageItem> =>this.write(channelId, async (tx, { member }) => {diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex bba75c906ff..cc63f870a55 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -1,4 +1,4 @@-import { channelMessageReceipt, channelMessageVia } from '@lobechat/types';+import { channelMessageEditedAt, channelMessageReceipt, channelMessageVia } from '@lobechat/types';import {and,asc,@@ -72,6 +72,7 @@ const publicMessage = (row: MessageRow, fileIds: string[]) => {name: isAgent ? senderAgentName || senderAgentTitle : senderUserName || senderUsername,type: isAgent ? ('agent' as const) : ('user' as const),},+ editedAt: channelMessageEditedAt(message.metadata),receipt: isAgent ? null : (channelMessageReceipt(message.metadata) ?? null),via: isAgent? nulldiff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex b2de7399115..6834c9739de 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -210,6 +210,14 @@ export const channelMessageReceipt = (: undefined;};+/** When a person last edited their message (`metadata.editedAt`); null if never. */+export const channelMessageEditedAt = (+ metadata: ChannelMessageMetadata | null | undefined,+): Date | null => {+ const editedAt = metadata?.editedAt;+ return typeof editedAt === 'string' ? new Date(editedAt) : null;+};+/** `metadata.via` of a relayed request, or undefined for anything else. */export const channelMessageVia = (metadata: ChannelMessageMetadata | null | undefined,@@ -541,6 +549,8 @@ export interface ChannelPublicMessage {};content: string;createdAt: Date;+ /** Set once the author has edited the text; shown as "(edited)". */+ editedAt?: Date | null;fileIds: string[];id: string;mentions: string[];