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(channel): don't count an Agent's opening acknowledgement as thread unread news (#23429)

Lobehub Codercb13873cad7a
diff --git a/packages/database/src/repositories/channel/__tests__/view.test.ts b/packages/database/src/repositories/channel/__tests__/view.test.ts
index a2bca1bcbe4..3b42e2bbd52 100644
--- a/packages/database/src/repositories/channel/__tests__/view.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/view.test.ts
@@ -5,6 +5,8 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
import { channelJobs, channelMembers, channelMessages } from '../../../schemas';
import { ChannelExecutionRepository, ChannelRepository } from '..';
+import { appendMessage } from '../delivery';
+import { openingRequestKey } from '../opening';
import { createChannelFixture, jobsOf, lease } from './testUtils';
const db = await getTestDB();
@@ -224,6 +226,7 @@ describe('Channel public view', () => {
const main = await asOwner.detail(channel.id);
expect(main.threads.find((entry) => entry.id === thread.id)).toMatchObject({
+ lastNewsAt: expect.any(Date),
lastReply: { author: { type: 'user' }, content: 'Latest reply' },
replyCount: 2,
});
@@ -240,6 +243,57 @@ describe('Channel public view', () => {
);
});
+ it('does not count an Agent acknowledgement as unread news in a thread summary', async () => {
+ const { asOwner, channel } = await fixture.createTeamChannel();
+ const agent = await fixture.addAgent(channel.id, 'Researcher');
+ const acked = await asOwner.send(channel.id, {
+ content: 'Acked root',
+ requestKey: 'acked',
+ routing: 'fallback',
+ });
+ const busy = await asOwner.send(channel.id, {
+ content: 'Busy root',
+ requestKey: 'busy',
+ routing: 'fallback',
+ });
+ const fresh = await asOwner.createThread(channel.id, { rootMessageId: acked.id });
+ const ongoing = await asOwner.createThread(channel.id, { rootMessageId: busy.id });
+ const person = await asOwner.send(channel.id, {
+ content: 'Unread person reply',
+ requestKey: 'person',
+ routing: 'fallback',
+ threadId: ongoing.id,
+ });
+ const ack = (threadId: string, jobId: string, replyToId: string) =>
+ db.transaction((tx) =>
+ appendMessage(tx, {
+ agentId: agent.agentId,
+ channelId: channel.id,
+ content: 'On it',
+ replyToId,
+ requestKey: openingRequestKey(jobId),
+ routingStatus: 'reply',
+ threadId,
+ }),
+ );
+ await ack(fresh.id, 'job_fresh', acked.id);
+ await ack(ongoing.id, 'job_ongoing', person.id);
+
+ const { threads } = await asOwner.detail(channel.id);
+ // The acknowledgement still previews what is happening, but is not news on its own.
+ expect(threads.find((entry) => entry.id === fresh.id)).toMatchObject({
+ lastNewsAt: null,
+ lastReply: { author: { type: 'agent' }, content: 'On it' },
+ replyCount: 1,
+ });
+ // Nor does it hide the earlier reply that still is.
+ expect(threads.find((entry) => entry.id === ongoing.id)).toMatchObject({
+ lastNewsAt: person.createdAt,
+ lastReply: { content: 'On it' },
+ replyCount: 2,
+ });
+ });
+
it.each([false, true])(
'includes the reply author so a new thread can answer without a mention (workspace: %s)',
async (workspace) => {
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 0cc26b62864..68eecc4f256 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -14,6 +14,7 @@ import {
inArray,
isNotNull,
isNull,
+ like,
lt,
or,
type SQL,
@@ -178,7 +179,20 @@ const sourceTopicsByMessage = async (
const THREAD_PREVIEW_LENGTH = 240;
+/**
+ * Request keys of the acknowledgements an Agent posts before its run (`openingRequestKey` in
+ * `./opening`, which imports this module, so the prefix is repeated here).
+ */
+const OPENING_REQUEST_KEY_PATTERN = 'opening:%';
+
+/** An Agent's acknowledgement before its run: it says the work started, not what came of it. */
+const isOpeningAck = and(
+ eq(channelMessages.routingStatus, 'reply'),
+ like(channelMessages.requestKey, OPENING_REQUEST_KEY_PATTERN),
+);
+
type ThreadSummary = {
+ lastNewsAt: Date | null;
lastReply: Pick<ReturnType<typeof publicMessage>, 'author' | 'content' | 'createdAt' | 'id'>;
replyCount: number;
};
@@ -192,7 +206,14 @@ const threadSummaries = async (tx: Transaction, channelId: string, threadIds: st
);
const [counts, latest] = await Promise.all([
tx
- .select({ replyCount: count(), threadId: channelMessages.threadId })
+ .select({
+ lastNewsAt:
+ sql<Date | null>`max(${channelMessages.createdAt}) filter (where not (${isOpeningAck}))`.mapWith(
+ channelMessages.createdAt,
+ ),
+ replyCount: count(),
+ threadId: channelMessages.threadId,
+ })
.from(channelMessages)
.where(scope)
.groupBy(channelMessages.threadId),
@@ -204,15 +225,16 @@ const threadSummaries = async (tx: Transaction, channelId: string, threadIds: st
.where(scope)
.orderBy(asc(channelMessages.threadId), desc(channelMessages.sequence)),
]);
- const replyCounts = new Map(counts.map((row) => [row.threadId, row.replyCount]));
+ const countsByThread = new Map(counts.map((row) => [row.threadId, row]));
return new Map<string, ThreadSummary>(
latest.map((row) => {
const { author, content, createdAt, id } = publicMessage(row, []);
return [
row.threadId!,
{
+ lastNewsAt: countsByThread.get(row.threadId)?.lastNewsAt ?? null,
lastReply: { author, content: content.slice(0, THREAD_PREVIEW_LENGTH), createdAt, id },
- replyCount: replyCounts.get(row.threadId) ?? 0,
+ replyCount: countsByThread.get(row.threadId)?.replyCount ?? 0,
},
];
}),
@@ -519,6 +541,7 @@ export const readChannelView = async (
return summarized.includes(entry.id)
? {
...named,
+ lastNewsAt: summaries.get(entry.id)?.lastNewsAt ?? null,
lastReply: summaries.get(entry.id)?.lastReply ?? null,
replyCount: summaries.get(entry.id)?.replyCount ?? 0,
}
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index b77f0358b96..af0734ce555 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -779,6 +779,12 @@ export type ChannelReplyJob = Pick<
export interface ChannelPublicThread {
followerMemberIds: string[];
id: string;
+ /**
+ * When the newest reply worth reporting as unread was posted: an Agent's acknowledgement before
+ * its run is not, so it does not mark the thread unread while its preview still shows. Null when
+ * the thread holds only acknowledgements; present under the same conditions as `lastReply`.
+ */
+ lastNewsAt?: Date | null;
/**
* The newest reply, for threads whose root is on the loaded main-timeline page. Absent in
* thread views and in views cached before summaries existed.