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): continue an earlier Thread only for the Agent's own live follow-up (#23576)

Arvin Xu18db6d97a7b0
diff --git a/apps/server/src/services/channel/opener.test.ts b/apps/server/src/services/channel/opener.test.ts
index e6454dd3205..0c112b84282 100644
--- a/apps/server/src/services/channel/opener.test.ts
+++ b/apps/server/src/services/channel/opener.test.ts
@@ -45,7 +45,7 @@ describe('createChannelReplyOpener', () => {
const [payload, options] = mockGenerateObject.mock.calls[0];
expect(options.tracing).toMatchObject({
agentId: 'agt',
- promptVersion: 'v1',
+ promptVersion: 'v2',
scenario: 'channel_reply_opener',
schemaName: 'channel_reply_opener',
});
diff --git a/apps/server/src/services/channel/replyOpening.ts b/apps/server/src/services/channel/replyOpening.ts
index 09002c96c88..12ad8e34788 100644
--- a/apps/server/src/services/channel/replyOpening.ts
+++ b/apps/server/src/services/channel/replyOpening.ts
@@ -88,10 +88,16 @@ const decide = async (
name: agentDisplayName(agent) || undefined,
title: agent.title ?? undefined,
})),
+ ...(candidate.request.fileIds?.length && {
+ attachmentCount: candidate.request.fileIds.length,
+ }),
message: candidate.request.content,
// Woken by its own rules, not asked: it acknowledges only a clear request for work.
...(!candidate.addressed && { notAddressed: true }),
recentMessages: candidate.recent.map((message) => describe(message, candidate.agent.id)),
+ ...(candidate.quoted && {
+ quoted: excerpt(describe(candidate.quoted, candidate.agent.id)),
+ }),
threads: candidate.threads.map((thread, index) => ({
label: threadLabel(index),
lastMessage: excerpt(thread.lastMessage),
diff --git a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts
index b7e20deeac4..770c774cdd5 100644
--- a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts
@@ -649,6 +649,95 @@ describe('Channel reply opening', () => {
expect((await execution.openingCandidate(channel.id, followUpJob.id))?.threads).toEqual([]);
});
+ it('leaves out a Thread the Agent never answered in', async () => {
+ const { channel, asMember, thread } = await answeredInThread();
+ const reviewer = await fixture.addAgent(channel.id, 'Reviewer');
+ const request = await asMember.send(channel.id, {
+ content: 'Clone the repo and map its frontend',
+ mentions: [reviewer.id],
+ requestKey: 'reviewer',
+ routing: 'decision',
+ });
+ const [job] = await jobsOf(db, request.id);
+
+ expect((await execution.openingCandidate(channel.id, job.id))?.threads).toEqual([]);
+ // Nor can the opener move it there by naming the Thread.
+ await execution.open(channel.id, job.id, { ack: 'Looking.', threadId: thread.id });
+ expect((await jobById(db, job.id)).threadId).toBeNull();
+ });
+
+ it('leaves out a Thread quiet for hours before the request', async () => {
+ const { channel, followUpJob, thread } = await answeredInThread();
+ const longAgo = new Date(Date.now() - 3 * 60 * 60 * 1000);
+ await db
+ .update(channelMessages)
+ .set({ createdAt: longAgo })
+ .where(eq(channelMessages.threadId, thread.id));
+ await db
+ .update(channelThreads)
+ .set({ createdAt: longAgo })
+ .where(eq(channelThreads.id, thread.id));
+
+ expect((await execution.openingCandidate(channel.id, followUpJob.id))?.threads).toEqual([]);
+ });
+
+ it('leaves out a Thread another Agent is answering in', async () => {
+ const { asMember, channel, followUpJob, thread } = await answeredInThread();
+ const reviewer = await fixture.addAgent(channel.id, 'Reviewer');
+ await asMember.send(channel.id, {
+ content: 'Review this too',
+ mentions: [reviewer.id],
+ requestKey: 'in-thread',
+ routing: 'decision',
+ threadId: thread.id,
+ });
+
+ expect((await execution.openingCandidate(channel.id, followUpJob.id))?.threads).toEqual([]);
+ });
+
+ it('offers only where a quoted request was answered, and hands the opener the quote', async () => {
+ const { agent, asMember, channel, message, thread } = await answeredInThread();
+ // A second request answered in place, on the main timeline.
+ const inPlace = await asMember.send(channel.id, {
+ content: 'Should the member list match the personal space?',
+ mentions: [agent.id],
+ requestKey: 'in-place',
+ routing: 'decision',
+ });
+ const [inPlaceJob] = await jobsOf(db, inPlace.id);
+ await execution.open(channel.id, inPlaceJob.id, {});
+
+ const quoting = await asMember.send(channel.id, {
+ content: 'Why is this UI still unchanged?',
+ mentions: [agent.id],
+ replyToId: inPlace.id,
+ requestKey: 'quoting',
+ routing: 'decision',
+ });
+ const [quotingJob] = await jobsOf(db, quoting.id);
+ const candidate = await execution.openingCandidate(channel.id, quotingJob.id);
+ expect(candidate?.threads).toEqual([]);
+ expect(candidate?.quoted).toMatchObject({
+ content: 'Should the member list match the personal space?',
+ id: inPlace.id,
+ });
+
+ // The first request, answered in the Thread.
+ const quotingRoot = await asMember.send(channel.id, {
+ content: 'Is this still failing?',
+ mentions: [agent.id],
+ replyToId: message.id,
+ requestKey: 'quoting-root',
+ routing: 'decision',
+ });
+ const [quotingRootJob] = await jobsOf(db, quotingRoot.id);
+ expect(
+ (await execution.openingCandidate(channel.id, quotingRootJob.id))?.threads.map(
+ ({ id }) => id,
+ ),
+ ).toEqual([thread.id]);
+ });
+
it('acknowledges on the main timeline with the Thread linked and answers inside it', async () => {
const { agent, asMember, channel, followUp, followUpJob, member, thread } =
await answeredInThread();
diff --git a/packages/database/src/repositories/channel/opening.ts b/packages/database/src/repositories/channel/opening.ts
index 99e0e1bdc6b..a8e70611091 100644
--- a/packages/database/src/repositories/channel/opening.ts
+++ b/packages/database/src/repositories/channel/opening.ts
@@ -1,5 +1,5 @@
import type { ChannelContextMessage, ChannelSharedAgentAccess } from '@lobechat/types';
-import { and, desc, eq, gte, inArray, isNull, lt, ne } from 'drizzle-orm';
+import { and, desc, eq, gte, inArray, isNull, lt, max, ne } from 'drizzle-orm';
import pMap from 'p-map';
import type { ChannelJobItem } from '../../schemas';
@@ -40,6 +40,15 @@ const OPENING_CONTEXT_LIMIT = 6;
*/
const OPENING_THREAD_LIMIT = 5;
+/** Threads read before the filters below, so some are left for {@link OPENING_THREAD_LIMIT}. */
+const OPENING_THREAD_SCAN_LIMIT = 20;
+
+/**
+ * How long a Thread may have been quiet before the request and still be continued. An older one
+ * is a finished conversation: picking it up again hides the new request in it.
+ */
+const OPENING_THREAD_IDLE_MS = 2 * 60 * 60 * 1000;
+
/** Threads described at once; each reads two messages. */
const OPENING_THREAD_READ_CONCURRENCY = 3;
@@ -87,6 +96,8 @@ export interface ChannelOpeningCandidate {
deviceId?: string;
/** The Agent's membership in this Channel, which its replies run as. */
memberId: string;
+ /** The message the request replies to, when its branch can read it. */
+ quoted?: ChannelContextMessage;
/** Public messages just before the request, oldest first. */
recent: ChannelContextMessage[];
request: ChannelContextMessage;
@@ -217,10 +228,7 @@ export const findOpeningCandidate = async (
if (!requester?.userId) return;
const [[request], [thread], [channel]] = await Promise.all([
- db
- .select({ sequence: channelMessages.sequence })
- .from(channelMessages)
- .where(eq(channelMessages.id, job.messageId)),
+ db.select(requestColumns).from(channelMessages).where(eq(channelMessages.id, job.messageId)),
job.threadId
? db
.select({ rootSequence: channelThreads.rootSequence })
@@ -234,21 +242,24 @@ export const findOpeningCandidate = async (
]);
if (!request || !channel) return;
// The request's branch up to the request itself, as the run's manifest will freeze it.
- const messages = await readManifestMessages(
- db,
- channelId,
- {
- cutoffSequence: request.sequence,
- requestMessageId: job.messageId,
- requesterMemberId: job.requesterMemberId,
- self: { agentId: row.agentId, memberId: job.memberId, name: '' },
- threadId: job.threadId,
- threadRootSequence: thread?.rootSequence ?? null,
- },
- { limit: OPENING_CONTEXT_LIMIT + 1 },
- );
+ const manifest = {
+ cutoffSequence: request.sequence,
+ requestMessageId: job.messageId,
+ requesterMemberId: job.requesterMemberId,
+ self: { agentId: row.agentId, memberId: job.memberId, name: '' },
+ threadId: job.threadId,
+ threadRootSequence: thread?.rootSequence ?? null,
+ };
+ const messages = await readManifestMessages(db, channelId, manifest, {
+ limit: OPENING_CONTEXT_LIMIT + 1,
+ });
const requestMessage = messages.find((message) => message.id === job.messageId);
if (!requestMessage) return;
+ const quotedId = requestMessage.replyToId;
+ const quoted = quotedId
+ ? (messages.find((message) => message.id === quotedId) ??
+ (await readManifestMessages(db, channelId, manifest, { messageId: quotedId }))[0])
+ : undefined;
const coAddressed = await coAddressedJobs(db, job);
return {
@@ -258,6 +269,7 @@ export const findOpeningCandidate = async (
coAddressed,
...(row.memberConfig?.deviceId && { deviceId: row.memberConfig.deviceId }),
memberId: job.memberId,
+ ...(quoted && { quoted }),
recent: messages.filter((message) => message.id !== job.messageId),
request: requestMessage,
requesterUserId: requester.userId,
@@ -266,11 +278,7 @@ export const findOpeningCandidate = async (
threads:
job.threadId || coAddressed.length
? []
- : await describeThreads(
- db,
- channelId,
- await recentOpenThreads(db, channelId, request.sequence),
- ),
+ : await describeThreads(db, channelId, await continuableThreads(db, job, request)),
workspaceId: channel.workspaceId,
};
};
@@ -529,36 +537,119 @@ const followThread = async (
.where(eq(channelThreads.id, thread.id));
};
-/** The open Threads started on the main timeline before `beforeSequence`, nearest first. */
-const recentOpenThreads = (
+/** What {@link continuableThreads} reads of the request. */
+const requestColumns = {
+ createdAt: channelMessages.createdAt,
+ replyToId: channelMessages.replyToId,
+ sequence: channelMessages.sequence,
+};
+
+/**
+ * Where the message a request quotes was answered, when it was a request itself: the Thread it
+ * sits in, or the Threads its own answers moved into (none when they stayed in place). Undefined
+ * when it quotes no request, such as a note nobody was asked about.
+ */
+const quotedRequestThreads = async (
db: LobeChatDatabase | Transaction,
channelId: string,
- beforeSequence: number,
-) =>
- db
- .select({
- followerMemberIds: channelThreads.followerMemberIds,
- id: channelThreads.id,
- metadata: channelThreads.metadata,
- rootMessageId: channelThreads.rootMessageId,
- })
- .from(channelThreads)
- .where(
- and(
- eq(channelThreads.channelId, channelId),
- lt(channelThreads.rootSequence, beforeSequence),
- ne(channelThreads.status, 'archived'),
- notTrashed(channelThreads.isDeleted),
+ replyToId: string | null,
+): Promise<Set<string> | undefined> => {
+ if (!replyToId) return;
+ const [quoted] = await db
+ .select({ threadId: channelMessages.threadId })
+ .from(channelMessages)
+ .where(and(eq(channelMessages.channelId, channelId), eq(channelMessages.id, replyToId)));
+ if (!quoted) return;
+ if (quoted.threadId) return new Set([quoted.threadId]);
+ const answers = await db
+ .select({ threadId: channelJobs.threadId })
+ .from(channelJobs)
+ .where(and(eq(channelJobs.channelId, channelId), eq(channelJobs.messageId, replyToId)));
+ if (!answers.length) return;
+ return new Set(answers.flatMap(({ threadId }) => (threadId ? [threadId] : [])));
+};
+
+/**
+ * The open Threads a job's reply may continue in, nearest first: started on the main timeline
+ * before the request, and still the Agent's own live conversation there.
+ *
+ * - The Agent follows it: it has answered there, so continuing is its own follow-up, not joining
+ * another Agent's work on a related subject.
+ * - It was active within {@link OPENING_THREAD_IDLE_MS} of the request.
+ * - No other Agent is answering in it right now.
+ * - When the request quotes another request, it is where that one was answered: "this" means the
+ * quoted message, not whatever Thread sits nearest.
+ */
+const continuableThreads = async (
+ db: LobeChatDatabase | Transaction,
+ job: Pick<ChannelJobItem, 'channelId' | 'memberId'>,
+ request: { createdAt: Date; replyToId: string | null; sequence: number },
+) => {
+ const { channelId } = job;
+ const [scanned, quotedIn] = await Promise.all([
+ db
+ .select({
+ createdAt: channelThreads.createdAt,
+ followerMemberIds: channelThreads.followerMemberIds,
+ id: channelThreads.id,
+ metadata: channelThreads.metadata,
+ rootMessageId: channelThreads.rootMessageId,
+ })
+ .from(channelThreads)
+ .where(
+ and(
+ eq(channelThreads.channelId, channelId),
+ lt(channelThreads.rootSequence, request.sequence),
+ ne(channelThreads.status, 'archived'),
+ notTrashed(channelThreads.isDeleted),
+ ),
+ )
+ .orderBy(desc(channelThreads.rootSequence))
+ .limit(OPENING_THREAD_SCAN_LIMIT),
+ quotedRequestThreads(db, channelId, request.replyToId),
+ ]);
+ const followed = scanned.filter(
+ (thread) =>
+ thread.followerMemberIds.includes(job.memberId) && (!quotedIn || quotedIn.has(thread.id)),
+ );
+ if (!followed.length) return [];
+
+ const ids = followed.map(({ id }) => id);
+ const [activity, busy] = await Promise.all([
+ db
+ .select({ at: max(channelMessages.createdAt), threadId: channelMessages.threadId })
+ .from(channelMessages)
+ .where(and(eq(channelMessages.channelId, channelId), inArray(channelMessages.threadId, ids)))
+ .groupBy(channelMessages.threadId),
+ db
+ .select({ threadId: channelJobs.threadId })
+ .from(channelJobs)
+ .where(
+ and(
+ eq(channelJobs.channelId, channelId),
+ inArray(channelJobs.threadId, ids),
+ inArray(channelJobs.status, ['queued', 'running']),
+ ne(channelJobs.memberId, job.memberId),
+ ),
),
- )
- .orderBy(desc(channelThreads.rootSequence))
- .limit(OPENING_THREAD_LIMIT);
+ ]);
+ const lastActive = new Map(activity.map(({ at, threadId }) => [threadId, at]));
+ const answering = new Set(busy.map(({ threadId }) => threadId));
+ const since = request.createdAt.getTime() - OPENING_THREAD_IDLE_MS;
+
+ return followed
+ .filter((thread) => {
+ const active = lastActive.get(thread.id) ?? thread.createdAt;
+ return active.getTime() >= since && !answering.has(thread.id);
+ })
+ .slice(0, OPENING_THREAD_LIMIT);
+};
/** What the opener reads of each Thread: its name, where it started and where it is now. */
const describeThreads = async (
db: LobeChatDatabase,
channelId: string,
- threads: Awaited<ReturnType<typeof recentOpenThreads>>,
+ threads: Awaited<ReturnType<typeof continuableThreads>>,
): Promise<ChannelOpeningThread[]> =>
pMap(
threads,
@@ -605,11 +696,11 @@ const describeThreads = async (
const continuableThread = async (tx: Transaction, job: ChannelJobItem, threadId: string) => {
if (job.threadId || (await coAddressedJobs(tx, job)).length) return;
const [request] = await tx
- .select({ sequence: channelMessages.sequence })
+ .select(requestColumns)
.from(channelMessages)
.where(eq(channelMessages.id, job.messageId));
if (!request) return;
- const threads = await recentOpenThreads(tx, job.channelId, request.sequence);
+ const threads = await continuableThreads(tx, job, request);
return threads.find((thread) => thread.id === threadId);
};
diff --git a/packages/prompts/src/chains/channelReplyOpener.ts b/packages/prompts/src/chains/channelReplyOpener.ts
index 6b29ee7adac..7ba6648bc68 100644
--- a/packages/prompts/src/chains/channelReplyOpener.ts
+++ b/packages/prompts/src/chains/channelReplyOpener.ts
@@ -1,6 +1,6 @@
import type { OpenAIChatMessage } from '@lobechat/types';
-export const CHANNEL_REPLY_OPENER_PROMPT_VERSION = 'v1';
+export const CHANNEL_REPLY_OPENER_PROMPT_VERSION = 'v2';
/**
* Where a Channel reply continues: in place, in a new Thread under it, or in one of the Threads
@@ -38,9 +38,10 @@ Fields:
- "ack": when "acknowledge" is true, one short sentence posted right away, in the language of the message and in your own voice. Never the answer itself, no time estimates, no greeting, no emoji. Empty string when "acknowledge" is false.
- "placement": where the conversation continues.
- "channel": a reply that fits in a message or two and needs no back-and-forth. Prefer it whenever the answer is short, even when the subject has a thread.
- - "existing_thread": the message continues the subject of one of the open threads listed below (a follow-up, a correction, more detail on the same problem), and the reply is longer than a message or two. Pick it only when the subject is clearly the same, not merely the same broad area.
- - "thread": a new subject whose reply is long, has several steps, or will likely need follow-up questions.
+ - "thread": a new task whose reply is long, has several steps, or will likely need follow-up questions. A new feature, a new change, a new bug or a new thing to analyze is a new task, even when it touches the same product area, files or feature as an open thread.
+ - "existing_thread": only when the message cannot be understood without one of the open threads listed below: it reacts to that thread's last result ("still broken", "try again", "that's not it", "also do it there"), corrects it, or names that thread. The reply must also be longer than a message or two. Sharing words or a product area with a thread is not enough; when unsure, choose "thread".
When the message says where to answer, follow it.
+ When the message quotes another message, "this" and "that" refer to the quoted message, not to an open thread. When it has attachments you cannot see, "this" refers to them.
- "title": when "placement" is "thread", a short title for the new thread in the language of the message, naming the subject (not "Request" or "Question"). Empty string otherwise.
- "thread": when "placement" is "existing_thread", the label of the chosen thread exactly as listed (for example "T2"). Empty string otherwise.
@@ -92,6 +93,8 @@ export interface ChannelReplyOpenerThread {
export interface ChannelReplyOpenerInput {
/** The agent behind the assistant: what it is named and its title (identity or role). */
agent?: { name?: string; title?: string };
+ /** Images or files sent with the message, which the opener cannot see. */
+ attachmentCount?: number;
/** Names people call the assistant by in this Channel. */
botNames?: string[];
/** Whether the reply can move into a Thread; false when the request is already in one. */
@@ -101,6 +104,8 @@ export interface ChannelReplyOpenerInput {
message: string;
/** Acknowledge only a clear request for work: woken without being addressed. */
notAddressed?: boolean;
+ /** The message this one replies to, as "Author: text". */
+ quoted?: string;
/** Short transcript of the messages just before this one, oldest first. */
recentMessages?: string[];
/** Open Threads started before the request, nearest first. */
@@ -145,9 +150,15 @@ const buildState = (input: ChannelReplyOpenerInput): string => {
if (input.recentMessages?.length) {
sections.push(`Earlier messages (oldest first):\n${input.recentMessages.join('\n')}`);
}
+ if (input.quoted) sections.push(`The message quotes:\n"""\n${input.quoted.trim()}\n"""`);
sections.push(
`${input.notAddressed ? 'Message' : 'Message to you'}:\n"""\n${input.message.trim()}\n"""`,
);
+ if (input.attachmentCount) {
+ sections.push(
+ `The message comes with ${input.attachmentCount} attachment(s), such as screenshots, that you cannot see.`,
+ );
+ }
return sections.join('\n\n');
};
diff --git a/packages/prompts/src/chains/generationContracts.test.ts b/packages/prompts/src/chains/generationContracts.test.ts
index c0d9e56e01d..9445e3c54ee 100644
--- a/packages/prompts/src/chains/generationContracts.test.ts
+++ b/packages/prompts/src/chains/generationContracts.test.ts
@@ -189,7 +189,7 @@ describe('application generation chains', () => {
],
});
- expect(CHANNEL_REPLY_OPENER_PROMPT_VERSION).toBe('v1');
+ expect(CHANNEL_REPLY_OPENER_PROMPT_VERSION).toBe('v2');
expect(CHANNEL_REPLY_OPENER_JSON_SCHEMA.name).toBe('channel_reply_opener');
expect(CHANNEL_REPLY_OPENER_JSON_SCHEMA.schema.properties.placement.enum).toEqual([
'channel',
@@ -209,6 +209,26 @@ describe('application generation chains', () => {
).not.toContain('existing_thread');
});
+ it('shows the Channel opener the quoted message and the attachments it cannot see', () => {
+ const { messages } = chainChannelReplyOpener({
+ attachmentCount: 2,
+ canOpenThread: true,
+ message: '你看下这个的 UI,咋还没改啊?',
+ quoted: 'Arvin: 个人空间下,群成员模式应该和这个一样才对',
+ threads: [{ label: 'T1', title: '优化 Loading 加载样式' }],
+ });
+
+ expect(messages[0].content).toContain('a new task, even when it touches the same product area');
+ expect(messages[0].content).toContain('"this" and "that" refer to the quoted message');
+ expect(messages[1].content).toContain(
+ 'The message quotes:\n"""\nArvin: 个人空间下,群成员模式应该和这个一样才对\n"""',
+ );
+ expect(messages[1].content).toContain('2 attachment(s)');
+ expect(
+ chainChannelReplyOpener({ canOpenThread: true, message: 'hi' }).messages[1].content,
+ ).not.toMatch(/quotes:|attachment/);
+ });
+
it('offers no existing Thread to a Channel opener asked with others or without threads', () => {
const threads = [{ label: 'T1', title: '表情包实现' }];
const together = chainChannelReplyOpener({