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.

✨ feat(channel): let a person delete their message, and an admin any message (#23298)

Arvin Xuc026f6ca7cba
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index e1091f37c57..e22eec72793 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -325,6 +325,12 @@ export const channelRouter = router({
data: await ctx.channelService.editMessage(input.channelId, input.messageId, input.content),
success: true,
})),
+ deleteMessage: channelProcedure
+ .input(z.object({ channelId, messageId: z.uuid() }))
+ .mutation(async ({ ctx, input }) => {
+ await ctx.channelService.deleteMessage(input.channelId, input.messageId);
+ return { success: true };
+ }),
/** An admin removes a person or an Agent from a group Channel. */
removeMember: channelProcedure
.input(z.object({ channelId, memberId: z.uuid() }))
diff --git a/apps/server/src/services/channel/ChannelService.ts b/apps/server/src/services/channel/ChannelService.ts
index 2bd5272030e..4b6d3a757e1 100644
--- a/apps/server/src/services/channel/ChannelService.ts
+++ b/apps/server/src/services/channel/ChannelService.ts
@@ -389,6 +389,13 @@ export class ChannelService {
return message;
};
+ /** Replies the message asked for stop with it; the coordinator stops those still writing. */
+ deleteMessage = async (channelId: string, messageId: string) => {
+ const writers = await this.repository.deleteMessage(channelId, messageId);
+ await new ChannelCoordinator(this.db).stopWriters(writers);
+ await Promise.all([wakeChannel(channelId), this.changed(channelId)]);
+ };
+
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__/claimGuards.test.ts b/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts
index 3041563e1a7..adca2deaed6 100644
--- a/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/claimGuards.test.ts
@@ -4,7 +4,13 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { UserModel } from '../../../models/user';
-import { channelJobs, channelMemberGrants, channelMembers, devices } from '../../../schemas';
+import {
+ channelJobs,
+ channelMemberGrants,
+ channelMembers,
+ channelMessages,
+ devices,
+} from '../../../schemas';
import type { LobeChatDatabase } from '../../../type';
import { ChannelExecutionRepository, ChannelRepository } from '..';
import { createChannelFixture, deviceConfig, jobsOf, lease } from './testUtils';
@@ -147,6 +153,21 @@ describe('claim guards', () => {
expect((await jobById(job.id)).status).toBe('cancelled');
});
+ it('cancels a job whose request was deleted while it waited', async () => {
+ const { asMember, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Coder');
+ const { job, message } = await request(asMember, channel.id, agent.id, 'withdrawn');
+
+ // Deletion racing the claim: the tombstone lands while the job is still queued.
+ await db
+ .update(channelMessages)
+ .set({ metadata: { deletedAt: new Date().toISOString() } })
+ .where(eq(channelMessages.id, message.id));
+
+ expect(await execution.claim(channel.id, job.id, lease)).toBeNull();
+ expect((await jobById(job.id)).status).toBe('cancelled');
+ });
+
it('gives a retried routing request the history up to itself', async () => {
const { asMember, channel } = await fixture.createTeamChannel();
const agent = await fixture.addAgent(channel.id, 'Coder');
diff --git a/packages/database/src/repositories/channel/__tests__/deleteMessage.test.ts b/packages/database/src/repositories/channel/__tests__/deleteMessage.test.ts
new file mode 100644
index 00000000000..771145b0c7b
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/deleteMessage.test.ts
@@ -0,0 +1,106 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { ChannelExecutionRepository } from '..';
+import { createChannelFixture, jobsOf, lease } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-delete-message');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const execution = new ChannelExecutionRepository(db);
+
+describe('ChannelRepository.deleteMessage', () => {
+ it('leaves a tombstone every member sees, without text or mentions', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const sent = await asMember.send(channel.id, {
+ content: 'Oops',
+ requestKey: 'oops',
+ routing: 'fallback',
+ });
+
+ await asMember.deleteMessage(channel.id, sent.id);
+
+ const [seen] = (await asOwner.detail(channel.id)).messages;
+ expect(seen).toMatchObject({ content: '', fileIds: [], id: sent.id, mentions: [] });
+ expect(seen.deletedAt).toBeInstanceOf(Date);
+ // Deleting again changes nothing.
+ await expect(asMember.deleteMessage(channel.id, sent.id)).resolves.toEqual([]);
+ });
+
+ it('lets only the author or an admin delete', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const ownerMessage = await asOwner.send(channel.id, {
+ content: 'Owner',
+ requestKey: 'owner',
+ routing: 'fallback',
+ });
+ const memberMessage = await asMember.send(channel.id, {
+ content: 'Member',
+ requestKey: 'member',
+ routing: 'fallback',
+ });
+
+ await expect(asMember.deleteMessage(channel.id, ownerMessage.id)).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ await expect(asOwner.deleteMessage(channel.id, memberMessage.id)).resolves.toEqual([]);
+ });
+
+ it('stops the replies the message asked for', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ await fixture.addAgent(channel.id, 'Device Agent');
+ const sent = await asOwner.send(channel.id, {
+ content: 'Do it',
+ requestKey: 'work',
+ routing: 'fallback',
+ });
+ const [job] = await jobsOf(db, sent.id);
+ await execution.claim(channel.id, job.id, lease);
+
+ const writers = await asOwner.deleteMessage(channel.id, sent.id);
+
+ expect(writers.map((writer) => writer.id)).toEqual([job.id]);
+ const [stopped] = await jobsOf(db, sent.id);
+ expect(stopped).toMatchObject({ publicationRevoked: true, status: 'cancelled' });
+ });
+
+ it('refuses to edit a tombstone back into a message', async () => {
+ const { asMember, asOwner, channel } = await fixture.createTeamChannel();
+ const sent = await asMember.send(channel.id, {
+ content: 'Oops',
+ requestKey: 'oops',
+ routing: 'fallback',
+ });
+
+ await asMember.deleteMessage(channel.id, sent.id);
+
+ await expect(asMember.editMessage(channel.id, sent.id, 'Back again')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ const [seen] = (await asOwner.detail(channel.id)).messages;
+ expect(seen).toMatchObject({ content: '', deletedAt: expect.any(Date), id: sent.id });
+ });
+
+ it('refuses to route a deleted message again', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ await fixture.addAgent(channel.id, 'Coder');
+ const sent = await asOwner.send(channel.id, {
+ content: 'Who knows?',
+ requestKey: 'who',
+ routing: 'decision',
+ });
+
+ // A pending message deleted before routing finished is left `unassigned`, which is exactly
+ // the status `retryRouting` accepts.
+ await asOwner.deleteMessage(channel.id, sent.id);
+
+ await expect(asOwner.retryRouting(channel.id, sent.id)).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ const [kept] = (await asOwner.detail(channel.id)).messages;
+ expect(kept).toMatchObject({ content: '', deletedAt: expect.any(Date), id: sent.id });
+ });
+});
diff --git a/packages/database/src/repositories/channel/__tests__/retryJob.test.ts b/packages/database/src/repositories/channel/__tests__/retryJob.test.ts
index 113ac8f8f59..0f894729a08 100644
--- a/packages/database/src/repositories/channel/__tests__/retryJob.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/retryJob.test.ts
@@ -35,7 +35,7 @@ const failedReply = async (
.where(eq(agentOperations.id, claimed.operationId!));
await execution.fail(team.channel.id, job.id, { message: 'Agent could not start' });
if (released) await execution.releaseWriter(team.channel.id, job.id);
- return { ...team, failed: claimed };
+ return { ...team, failed: claimed, message };
};
const deviceUnreachable = {
@@ -96,4 +96,15 @@ describe('Retrying a reply that could not reach its device', () => {
code: 'CONFLICT',
});
});
+
+ it('refuses to retry a reply whose request was deleted', async () => {
+ const { asOwner, channel, failed, message } = await failedReply(deviceUnreachable);
+
+ await asOwner.deleteMessage(channel.id, message.id);
+
+ await expect(asOwner.retryJob(channel.id, failed.id)).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect((await asOwner.detail(channel.id)).jobs[0]).toMatchObject({ status: 'failed' });
+ });
});
diff --git a/packages/database/src/repositories/channel/claim.ts b/packages/database/src/repositories/channel/claim.ts
index 668ed96824e..0f2302982ef 100644
--- a/packages/database/src/repositories/channel/claim.ts
+++ b/packages/database/src/repositories/channel/claim.ts
@@ -1,4 +1,5 @@
import type { ChannelExecutionConfig, ChannelJobBlockCode, LobeAgentConfig } from '@lobechat/types';
+import { channelMessageDeletedAt } from '@lobechat/types';
import { and, asc, eq, isNotNull, isNull, lt, or, sql } from 'drizzle-orm';
import type { PartialDeep } from 'type-fest';
@@ -279,6 +280,12 @@ export const claimJob = async (
.select()
.from(channelMessages)
.where(eq(channelMessages.id, job.messageId));
+ // A request deleted while this job waited must not run: its tombstone carries no text or
+ // mentions, so the run would answer a message that no longer exists.
+ if (channelMessageDeletedAt(request.metadata)) {
+ await cancel(tx, job, 'request_deleted');
+ return null;
+ }
// An earlier undecided message in this branch may still enqueue this member ahead of it, and
// so may the Thread's root while it is undecided. Checking only jobs would let a later
// request overtake it while another worker routes it. Other branches never hold this one.
diff --git a/packages/database/src/repositories/channel/delete.ts b/packages/database/src/repositories/channel/delete.ts
new file mode 100644
index 00000000000..1f67aa15991
--- /dev/null
+++ b/packages/database/src/repositories/channel/delete.ts
@@ -0,0 +1,69 @@
+import { channelMessageDeletedAt } from '@lobechat/types';
+import { and, eq, inArray, sql } from 'drizzle-orm';
+
+import type { ChannelJobItem } from '../../schemas';
+import { channelJobs, channelMessageFiles, channelMessages } from '../../schemas';
+import type { Transaction } from '../../type';
+import { assertThreadOpen, findThread } from './delivery';
+import { ChannelError } from './error';
+import { stopScope } from './stop';
+import { audit } from './transaction';
+import { OPEN_JOB_STATUSES } from './writer';
+
+/**
+ * Deletes a message: a person their own, an admin anyone's, Agent replies included. The row
+ * stays as a tombstone (`metadata.deletedAt`) without text, mentions or attachments, so a Thread
+ * started from it, replies quoting it and the jobs it asked for still resolve. Replies it asked
+ * for that are still queued or running stop, and routing still deciding is closed.
+ *
+ * Returns the jobs whose writer is still held: the caller must stop them physically.
+ */
+export const deleteMessage = async (
+ tx: Transaction,
+ channelId: string,
+ caller: { admin: boolean; userId: string },
+ messageId: string,
+): Promise<ChannelJobItem[]> => {
+ 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 only an admin removes them.
+ const own = message.routingStatus !== 'reply' && message.userId === caller.userId;
+ if (!own && !caller.admin)
+ throw new ChannelError('FORBIDDEN', 'Only the author or an admin can delete a message');
+ if (channelMessageDeletedAt(message.metadata)) return [];
+ assertThreadOpen(await findThread(tx, channelId, message.threadId));
+
+ const open = await tx
+ .select({ id: channelJobs.id })
+ .from(channelJobs)
+ .where(
+ and(
+ eq(channelJobs.channelId, channelId),
+ eq(channelJobs.messageId, messageId),
+ inArray(channelJobs.status, OPEN_JOB_STATUSES),
+ ),
+ );
+ const writers: ChannelJobItem[] = [];
+ for (const job of open) writers.push(...(await stopScope(tx, channelId, { jobId: job.id })));
+
+ await tx
+ .update(channelMessages)
+ .set({
+ content: '',
+ mentions: [],
+ metadata: { ...message.metadata, deletedAt: new Date().toISOString() },
+ // A late decision model answer must not route a deleted message.
+ ...(message.routingStatus === 'pending' && {
+ routingAttempt: sql`${channelMessages.routingAttempt} + 1`,
+ routingReason: 'Deleted before routing finished',
+ routingStatus: 'unassigned' as const,
+ }),
+ })
+ .where(eq(channelMessages.id, messageId));
+ await tx.delete(channelMessageFiles).where(eq(channelMessageFiles.messageId, messageId));
+ await audit(tx, channelId, 'message_deleted', messageId);
+ return writers;
+};
diff --git a/packages/database/src/repositories/channel/edit.ts b/packages/database/src/repositories/channel/edit.ts
index 1545482bbbd..9e981fb1c59 100644
--- a/packages/database/src/repositories/channel/edit.ts
+++ b/packages/database/src/repositories/channel/edit.ts
@@ -1,4 +1,4 @@
-import { channelMessageEditedAt } from '@lobechat/types';
+import { channelMessageDeletedAt, channelMessageEditedAt } from '@lobechat/types';
import { and, count, eq } from 'drizzle-orm';
import { channelMessageFiles, channelMessages } from '../../schemas';
@@ -24,6 +24,9 @@ export const editMessage = async (
.from(channelMessages)
.where(and(eq(channelMessages.channelId, channelId), eq(channelMessages.id, messageId)));
if (!message) throw new ChannelError('NOT_FOUND', 'Message not found');
+ // A tombstone carries no content by design; editing one would put it back.
+ if (channelMessageDeletedAt(message.metadata))
+ throw new ChannelError('CONFLICT', 'A deleted message cannot be edited');
// 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');
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index e2a6f99f98c..22eda7053bf 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -34,6 +34,7 @@ import {
} from './agent';
import { openAgentPair } from './agentPair';
import { channelAvatarMembers } from './avatars';
+import { deleteMessage } from './delete';
import { findThread } from './delivery';
import { editMessage } from './edit';
import { ChannelError } from './error';
@@ -1101,6 +1102,17 @@ export class ChannelRepository {
editMessage = async (channelId: string, messageId: string, content: string) =>
this.write(channelId, (tx) => editMessage(tx, channelId, this.userId, messageId, content));
+ /** Deletes the caller's own message, or any as an admin; see `deleteMessage`. */
+ deleteMessage = async (channelId: string, messageId: string): Promise<ChannelJobItem[]> =>
+ this.write(channelId, (tx, { member }) =>
+ deleteMessage(
+ tx,
+ channelId,
+ { admin: hasRole(member.role, 'admin'), userId: this.userId },
+ messageId,
+ ),
+ );
+
/** 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/lastMessage.ts b/packages/database/src/repositories/channel/lastMessage.ts
index 92b5d812b45..10bb6ab9f1b 100644
--- a/packages/database/src/repositories/channel/lastMessage.ts
+++ b/packages/database/src/repositories/channel/lastMessage.ts
@@ -5,6 +5,7 @@ import { alias } from 'drizzle-orm/pg-core';
import { channelMessages, channelThreads } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { notTrashed } from '../../utils/softDelete';
+import { messageStands } from './tombstone';
/** Characters of the latest message a Channel list item carries as its preview. */
const LIST_PREVIEW_LENGTH = 200;
@@ -50,6 +51,7 @@ export const channelLastMessages = async (
.where(
and(
inArray(channelMessages.channelId, channelIds),
+ messageStands(),
or(isNull(channelMessages.threadId), notTrashed(channelThreads.isDeleted)),
),
)
diff --git a/packages/database/src/repositories/channel/manifest.ts b/packages/database/src/repositories/channel/manifest.ts
index ecddc57495c..8bb47bf9aed 100644
--- a/packages/database/src/repositories/channel/manifest.ts
+++ b/packages/database/src/repositories/channel/manifest.ts
@@ -18,6 +18,7 @@ import { agents, channelMessages, users } from '../../schemas';
import type { LobeChatDatabase, Transaction } from '../../type';
import { fileIdsByMessage } from './attachments';
import { isAgentAuthored } from './author';
+import { messageStands } from './tombstone';
/** Freeze the public history cutoff and branch for this request. */
export const buildManifest = (params: {
@@ -53,6 +54,8 @@ const manifestScope = (channelId: string, manifest: ChannelInputManifest) => {
return and(
eq(channelMessages.channelId, channelId),
lte(channelMessages.sequence, manifest.cutoffSequence),
+ // A message deleted after the manifest froze leaves the context it was in.
+ messageStands(),
threadId
? or(eq(channelMessages.threadId, threadId), mainPrefix)
: isNull(channelMessages.threadId),
diff --git a/packages/database/src/repositories/channel/retry.ts b/packages/database/src/repositories/channel/retry.ts
index 4463181a9b0..8e952f9e6a9 100644
--- a/packages/database/src/repositories/channel/retry.ts
+++ b/packages/database/src/repositories/channel/retry.ts
@@ -1,7 +1,8 @@
+import { channelMessageDeletedAt } from '@lobechat/types';
import { and, eq, sql } from 'drizzle-orm';
import type { ChannelJobItem } from '../../schemas';
-import { agentOperations, channelJobs } from '../../schemas';
+import { agentOperations, channelJobs, channelMessages } from '../../schemas';
import type { Transaction } from '../../type';
import { assertThreadOpen, findThread } from './delivery';
import { ChannelError } from './error';
@@ -12,11 +13,12 @@ const DEVICE_UNREACHABLE = 'DeviceGatewayNotConfigured';
/**
* Queues a reply that failed before it started again. Only a reply whose device could not be
- * reached qualifies, and only once its writer is released: nothing ran, nothing was accepted
- * or published, so running it again cannot repeat work. Deliveries are unique per message and
- * member, so the job itself goes back to the queue, keeping its place in message order. The
- * next claim reads the Agent's current settings and environment and opens a fresh operation;
- * the failed one stays on its topic as history.
+ * reached qualifies, only while its request still stands (a deleted request leaves a tombstone
+ * without text or mentions, so re-running it would answer nothing), and only once its writer is
+ * released: nothing ran, nothing was accepted or published, so running it again cannot repeat
+ * work. Deliveries are unique per message and member, so the job itself goes back to the queue,
+ * keeping its place in message order. The next claim reads the Agent's current settings and
+ * environment and opens a fresh operation; the failed one stays on its topic as history.
*/
export const retryJob = async (
tx: Transaction,
@@ -24,12 +26,21 @@ export const retryJob = async (
jobId: string,
): Promise<ChannelJobItem> => {
const [row] = await tx
- .select({ errorType: sql<string | null>`${agentOperations.error}->>'type'`, job: channelJobs })
+ .select({
+ errorType: sql<string | null>`${agentOperations.error}->>'type'`,
+ job: channelJobs,
+ request: channelMessages,
+ })
.from(channelJobs)
+ .innerJoin(channelMessages, eq(channelMessages.id, channelJobs.messageId))
.leftJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))
.where(and(eq(channelJobs.channelId, channelId), eq(channelJobs.id, jobId)));
if (!row) throw new ChannelError('NOT_FOUND', 'Job not found');
- const { errorType, job } = row;
+ const { errorType, job, request } = row;
+ // A withdrawn request must not restart work: the tombstone is left with no text or mentions,
+ // and the coordinator would still launch a run for it.
+ if (channelMessageDeletedAt(request.metadata))
+ throw new ChannelError('CONFLICT', 'The request was deleted');
assertThreadOpen(await findThread(tx, channelId, job.threadId));
if (
job.status !== 'failed' ||
diff --git a/packages/database/src/repositories/channel/routing.ts b/packages/database/src/repositories/channel/routing.ts
index 0fa483624bf..f36e68f7441 100644
--- a/packages/database/src/repositories/channel/routing.ts
+++ b/packages/database/src/repositories/channel/routing.ts
@@ -3,6 +3,7 @@ import type {
ChannelJobWake,
ChannelMessageRoutingStatus,
} from '@lobechat/types';
+import { channelMessageDeletedAt } from '@lobechat/types';
import { and, eq, sql } from 'drizzle-orm';
import type { ChannelMessageItem } from '../../schemas';
@@ -142,6 +143,10 @@ export const retryRouting = async (
): Promise<ChannelMessageItem> => {
const message = await findMessage(tx, channelId, messageId);
assertThreadOpen(await findThread(tx, channelId, message.threadId));
+ // A tombstone is `unassigned` after deletion; sending it back to the decision model would
+ // restart a request whose author already withdrew it.
+ if (channelMessageDeletedAt(message.metadata))
+ throw new ChannelError('CONFLICT', 'A deleted message cannot be routed again');
if (message.routingStatus !== 'unassigned')
throw new ChannelError('CONFLICT', 'Only an unassigned message can be routed again');
diff --git a/packages/database/src/repositories/channel/tombstone.ts b/packages/database/src/repositories/channel/tombstone.ts
new file mode 100644
index 00000000000..d255a07bd2d
--- /dev/null
+++ b/packages/database/src/repositories/channel/tombstone.ts
@@ -0,0 +1,15 @@
+import { sql } from 'drizzle-orm';
+
+import { channelMessages } from '../../schemas';
+
+/**
+ * A message not deleted. A deleted one stays as a tombstone (`metadata.deletedAt`) so Threads,
+ * replies and jobs that point at it still resolve; readers of its content skip it.
+ *
+ * The predicate is a qual on several read paths, so it must not null-test an extracted jsonb
+ * value directly: `(metadata ->> 'deletedAt') IS NULL` takes the planner down on any table that
+ * carries a bm25 index (see `models/__tests__/jsonbNullTest.test.ts`). COALESCE to a sentinel
+ * keeps the same meaning for a missing key or a JSON null, and costs nothing.
+ */
+export const messageStands = () =>
+ sql`COALESCE(${channelMessages.metadata} ->> 'deletedAt', '') = ''`;
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 803d6ab5705..57abb9a8cfb 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -1,4 +1,9 @@
-import { channelMessageEditedAt, channelMessageReceipt, channelMessageVia } from '@lobechat/types';
+import {
+ channelMessageDeletedAt,
+ channelMessageEditedAt,
+ channelMessageReceipt,
+ channelMessageVia,
+} from '@lobechat/types';
import {
and,
asc,
@@ -75,6 +80,7 @@ export const publicMessage = (row: MessageRow, fileIds: string[]) => {
name: isAgent ? senderAgentName || senderAgentTitle : senderUserName || senderUsername,
type: isAgent ? ('agent' as const) : ('user' as const),
},
+ deletedAt: channelMessageDeletedAt(message.metadata),
editedAt: channelMessageEditedAt(message.metadata),
// On an Agent's message, the exchange between Agents it reports from.
receipt: (() => {
@@ -460,8 +466,11 @@ export const readChannelView = async (
: [];
const quotes = new Map(
quoted.map((row) => {
- const { author, content, id, sequence, threadId } = publicMessage(row, []);
- return [id, { author, content: content.slice(0, 240), id, sequence, threadId }] as const;
+ const { author, content, deletedAt, id, sequence, threadId } = publicMessage(row, []);
+ return [
+ id,
+ { author, content: content.slice(0, 240), deletedAt, id, sequence, threadId },
+ ] as const;
}),
);
const files = await fileIdsByMessage(tx, [
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 0d7b4333dd4..e59a3303c8c 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -248,6 +248,14 @@ export const channelMessageReceipt = (
: undefined;
};
+/** When the message was deleted (`metadata.deletedAt`); null while it stands. */
+export const channelMessageDeletedAt = (
+ metadata: ChannelMessageMetadata | null | undefined,
+): Date | null => {
+ const deletedAt = metadata?.deletedAt;
+ return typeof deletedAt === 'string' ? new Date(deletedAt) : null;
+};
+
/** When a person last edited their message (`metadata.editedAt`); null if never. */
export const channelMessageEditedAt = (
metadata: ChannelMessageMetadata | null | undefined,
@@ -665,6 +673,11 @@ export interface ChannelPublicMessage {
};
content: string;
createdAt: Date;
+ /**
+ * Set once the message was deleted. Its row stays as a tombstone, without text, mentions or
+ * attachments, so Threads, replies and jobs that point at it still resolve.
+ */
+ deletedAt?: Date | null;
/** Set once the author has edited the text; shown as "(edited)". */
editedAt?: Date | null;
fileIds: string[];
@@ -676,7 +689,7 @@ export interface ChannelPublicMessage {
/** Bounded public quote, including when its original is outside the loaded page. */
replyTo?: Pick<
ChannelPublicMessage,
- 'id' | 'author' | 'content' | 'sequence' | 'threadId'
+ 'id' | 'author' | 'content' | 'deletedAt' | 'sequence' | 'threadId'
> | null;
replyToId: string | null;
routingStatus: ChannelMessageRoutingStatus;