🤯 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): in a group, open a long reply's Thread under the request and acknowledge inside it (#23268)
Arvin Xu299e95e49318
diff --git a/packages/database/src/repositories/channel/__tests__/openingLayout.test.ts b/packages/database/src/repositories/channel/__tests__/openingLayout.test.tsnew file mode 100644index 00000000000..2e503866dbd--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/openingLayout.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest';++import type { OpeningFacts } from '../openingLayout';+import { chooseOpeningLayout } from '../openingLayout';++const facts = (overrides: Partial<OpeningFacts>): OpeningFacts => ({+ acknowledges: true,+ inThread: false,+ requestHasArchivedThread: false,+ sharedTimeline: false,+ wantsThread: true,+ ...overrides,+});++describe('chooseOpeningLayout', () => {+ it.each([+ ['a short reply stays in place', { wantsThread: false }, 'inline'],+ ['a request inside a Thread stays there', { inThread: true, sharedTimeline: true }, 'inline'],+ ['a group opens the Thread under the request', { sharedTimeline: true }, 'underRequest'],+ [+ 'a group without an acknowledgement still opens under the request',+ { acknowledges: false, sharedTimeline: true },+ 'underRequest',+ ],+ ['one person hangs the Thread under the acknowledgement', {}, 'underAck'],+ [+ 'one person without an acknowledgement opens under the request',+ { acknowledges: false },+ 'underAck',+ ],+ [+ 'a group whose request has an archived Thread hangs it under the acknowledgement',+ { requestHasArchivedThread: true, sharedTimeline: true },+ 'underAck',+ ],+ [+ 'an archived Thread with nothing to hang a new one under stays in place',+ { acknowledges: false, requestHasArchivedThread: true, sharedTimeline: true },+ 'inline',+ ],+ ] as const)('%s', (_, overrides, layout) => {+ expect(chooseOpeningLayout(facts(overrides))).toBe(layout);+ });+});diff --git a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts b/packages/database/src/repositories/channel/__tests__/replyOpening.test.tsindex ea89d43adf0..83fcc223b92 100644--- a/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts+++ b/packages/database/src/repositories/channel/__tests__/replyOpening.test.ts@@ -74,7 +74,7 @@ describe('Channel reply opening', () => {expect((await jobById(db, job.id)).threadId).toBeNull();});- it('acknowledges in the main timeline and moves the reply into a named Thread under it', async () => {+ it('in a group with several people, opens the Thread under the request and acknowledges inside it', async () => {const { channel, job, member, message } = await mentionAgent();await execution.open(channel.id, job.id, {@@ -82,7 +82,18 @@ describe('Channel reply opening', () => {threadTitle: 'Deploy failure',});- // The acknowledgement answers the request where it was asked …+ // The Thread opens under the request …+ const [thread] = await db+ .select()+ .from(channelThreads)+ .where(eq(channelThreads.channelId, channel.id));+ expect(thread).toMatchObject({+ metadata: { title: 'Deploy failure' },+ rootMessageId: message.id,+ });+ expect(new Set(thread.followerMemberIds)).toEqual(new Set([member.id, job.memberId]));+ expect((await jobById(db, job.id)).threadId).toBe(thread.id);+ // … and the acknowledgement answers the request inside it, not on the shared timeline.const [ack] = await db.select().from(channelMessages)@@ -92,35 +103,71 @@ describe('Channel reply opening', () => {eq(channelMessages.requestKey, `opening:${job.id}`),),);- expect(ack).toMatchObject({ replyToId: message.id, threadId: null });- // … and the Thread opens under it.- const [thread] = await db- .select()- .from(channelThreads)- .where(eq(channelThreads.channelId, channel.id));- expect(thread).toMatchObject({ metadata: { title: 'Deploy failure' }, rootMessageId: ack.id });- expect(new Set(thread.followerMemberIds)).toEqual(new Set([member.id, job.memberId]));- expect((await jobById(db, job.id)).threadId).toBe(thread.id);+ expect(ack).toMatchObject({ replyToId: message.id, threadId: thread.id });// The run starts in the Thread, still sees the request, and its answer lands there.const claim = await execution.claim(channel.id, job.id, lease);expect(claim?.job.manifest).toMatchObject({cutoffSequence: message.sequence,threadId: thread.id,- threadRootSequence: ack.sequence,+ threadRootSequence: message.sequence,});expect((await execution.input(channel.id, job.id)).map(({ id }) => id)).toEqual([message.id]);+ expect(await execution.openingReply(channel.id, job.id)).toBe(+ 'On it, I will compare the two configs first.',+ );await execution.accepted(channel.id, job.id);await execution.saveDraft(channel.id, job.id, 'The token expired.');const replyId = await execution.publish(channel.id, job.id);const [reply] = await db.select().from(channelMessages).where(eq(channelMessages.id, replyId));expect(reply.threadId).toBe(thread.id);- const detail = await new ChannelRepository(db, fixture.memberId, fixture.workspaceId).detail(- channel.id,- );+ const repository = new ChannelRepository(db, fixture.memberId, fixture.workspaceId);+ const detail = await repository.detail(channel.id);expect(detail.threads).toEqual([expect.objectContaining({ title: 'Deploy failure' })]);- expect(detail.messages.map(({ id }) => id)).toEqual([message.id, ack.id]);+ expect(detail.messages.map(({ id }) => id)).toEqual([message.id]);+ const inThread = await repository.detail(channel.id, { threadId: thread.id });+ expect(inThread.messages.map(({ id }) => id)).toEqual([ack.id, replyId]);+ });++ it('with one person, acknowledges in the main timeline and moves the reply into a Thread under it', async () => {+ const repository = new ChannelRepository(db, fixture.ownerId, fixture.workspaceId);+ const { channel } = await repository.create({ title: 'Solo' });+ const agent = await fixture.addAgent(channel.id, 'Coder');+ const message = await repository.send(channel.id, {+ content: 'Why did yesterday’s deploy fail?',+ mentions: [agent.id],+ requestKey: 'solo',+ routing: 'decision',+ });+ const [job] = await jobsOf(db, message.id);++ await execution.open(channel.id, job.id, {+ ack: 'On it, I will compare the two configs first.',+ threadTitle: 'Deploy failure',+ });++ const [ack] = await db+ .select()+ .from(channelMessages)+ .where(+ and(+ eq(channelMessages.channelId, channel.id),+ eq(channelMessages.requestKey, `opening:${job.id}`),+ ),+ );+ expect(ack).toMatchObject({ replyToId: message.id, threadId: null });+ const [thread] = await db+ .select()+ .from(channelThreads)+ .where(eq(channelThreads.channelId, channel.id));+ expect(thread).toMatchObject({ metadata: { title: 'Deploy failure' }, rootMessageId: ack.id });+ expect((await jobById(db, job.id)).threadId).toBe(thread.id);+ const claim = await execution.claim(channel.id, job.id, lease);+ expect(claim?.job.manifest).toMatchObject({+ threadId: thread.id,+ threadRootSequence: ack.sequence,+ });});/** A request mentioning two Agents, one job each. */@@ -205,7 +252,7 @@ describe('Channel reply opening', () => {expect(await execution.claim(channel.id, job.id, lease)).not.toBeNull();});- it('opens a fresh Thread under the acknowledgement even when the request’s is archived', async () => {+ it('opens a fresh Thread under the acknowledgement when the request’s is archived', async () => {const { asOwner, channel, job, message } = await mentionAgent();const archived = await asOwner.createThread(channel.id, { rootMessageId: message.id });await asOwner.archiveThread(channel.id, archived.id);@@ -215,6 +262,8 @@ describe('Channel reply opening', () => {const { threadId } = await jobById(db, job.id);expect(threadId).not.toBeNull();expect(threadId).not.toBe(archived.id);+ const ack = (await messagesOf(channel.id)).find((row) => row.routingStatus === 'reply');+ expect(ack).toMatchObject({ threadId: null });expect(await execution.claim(channel.id, job.id, lease)).not.toBeNull();});diff --git a/packages/database/src/repositories/channel/opening.ts b/packages/database/src/repositories/channel/opening.tsindex 8ba74977a59..9e75376bd76 100644--- a/packages/database/src/repositories/channel/opening.ts+++ b/packages/database/src/repositories/channel/opening.ts@@ -14,6 +14,8 @@ import type { LobeChatDatabase, Transaction } from '../../type';import { notTrashed } from '../../utils/softDelete';import { appendMessage } from './delivery';import { readManifestMessages } from './manifest';+import type { OpeningFacts, OpeningLayout } from './openingLayout';+import { chooseOpeningLayout } from './openingLayout';import { audit, withChannelLock } from './transaction';import { createChannelThread } from './view';@@ -148,9 +150,9 @@ export const findOpeningCandidate = async (};/**- * Applies the opener's decision to a still-queued job, once: posts the acknowledgement as the- * replying Agent in the request's branch, then opens the Thread under it (under the request when- * there is none) and moves the job into it. Records the opening even when nothing was posted, so the opener is not asked again.+ * Applies the opener's decision to a still-queued job, once: picks the layout with+ * `chooseOpeningLayout`, then opens the Thread and posts the acknowledgement where it says.+ * Records the opening even when nothing was posted, so the opener is not asked again.* Returns false when another worker opened the job first or it already started.*/export const applyOpening = async (@@ -177,9 +179,16 @@ export const applyOpening = async (.where(and(eq(channelMembers.id, job.memberId), eq(channelMembers.status, 'active')));if (!member?.agentId) return false;- // The acknowledgement goes where the person is looking: the request's own branch, answering- // the request. A Thread opens under it, so the person sees the reply start and where it went.const ack = decision.ack?.trim();+ const title = decision.threadTitle?.trim().slice(0, THREAD_TITLE_LENGTH) ?? '';+ const layout = await planOpening(tx, channelId, job, { ack, title });++ let threadId = job.threadId;+ if (layout === 'underRequest')+ threadId = await openReplyThread(tx, channelId, job, job.messageId, title);++ // The acknowledgement answers the request where the reply continues: in place, or in the+ // Thread just opened under the request.const posted = ack? await appendMessage(tx, {agentId: member.agentId,@@ -188,63 +197,12 @@ export const applyOpening = async (replyToId: job.messageId,requestKey: openingRequestKey(job.id),routingStatus: 'reply',- threadId: job.threadId,+ threadId,}): undefined;- let threadId = job.threadId;- const title = decision.threadTitle?.trim().slice(0, THREAD_TITLE_LENGTH);- // Without an acknowledgement the Thread opens under the request itself, unless an archived- // one already sits there: it takes no new work, so the reply stays where it was asked.- const rootMessageId = posted?.id ?? job.messageId;- if (title && !threadId && !(await hasArchivedThread(tx, channelId, rootMessageId))) {- // Follow-ups deferred behind this answer move with it: they must read it to stay silent.- const deferred = await tx- .select({ id: channelJobs.id, memberId: channelJobs.memberId })- .from(channelJobs)- .where(- and(- eq(channelJobs.channelId, channelId),- eq(channelJobs.messageId, job.messageId),- eq(channelJobs.status, 'queued'),- isNull(channelJobs.threadId),- sql`${channelJobs.wake}->>'afterMemberId' = ${job.memberId}`,- ),- );- const candidates = [- ...new Set([- job.requesterMemberId,- job.memberId,- ...deferred.map(({ memberId }) => memberId),- ]),- ];- // A member who has left since the request no longer follows anything.- const followers = (- await tx- .select({ id: channelMembers.id })- .from(channelMembers)- .where(- and(- eq(channelMembers.channelId, channelId),- eq(channelMembers.status, 'active'),- inArray(channelMembers.id, candidates),- ),- )- ).map(({ id }) => id);- const thread = await createChannelThread(tx, channelId, {- followerMemberIds: followers,- rootMessageId,- });- // A Thread already open under the request (another Agent's answer without an- // acknowledgement, or one someone branched) keeps its name, and gains whoever answers in it.- await followThread(tx, thread, followers);- if (!thread.metadata?.title) await nameThread(tx, thread.id, title);- threadId = thread.id;- await tx- .update(channelJobs)- .set({ threadId })- .where(inArray(channelJobs.id, [job.id, ...deferred.map(({ id }) => id)]));- }+ if (layout === 'underAck')+ threadId = await openReplyThread(tx, channelId, job, posted?.id ?? job.messageId, title);await audit(tx, channelId, REPLY_OPENED_EVENT, job.id, {...(posted && { messageId: posted.id }),@@ -254,6 +212,97 @@ export const applyOpening = async (return true;});+/** Gathers the facts `chooseOpeningLayout` needs, reading the Channel only when a Thread is wanted. */+const planOpening = async (+ tx: Transaction,+ channelId: string,+ job: typeof channelJobs.$inferSelect,+ decision: { ack?: string; title: string },+): Promise<OpeningLayout> => {+ const wantsThread = !!decision.title;+ const inThread = !!job.threadId;+ const facts: OpeningFacts = {+ acknowledges: !!decision.ack,+ inThread,+ requestHasArchivedThread: false,+ sharedTimeline: false,+ wantsThread,+ };+ if (wantsThread && !inThread) {+ facts.sharedTimeline = await hasSeveralPeople(tx, channelId);+ facts.requestHasArchivedThread = await hasArchivedThread(tx, channelId, job.messageId);+ }+ return chooseOpeningLayout(facts);+};++/** Whether more than one person is in the Channel, so its main timeline is shared. */+const hasSeveralPeople = async (tx: Transaction, channelId: string) => {+ const people = await tx+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channelId),+ eq(channelMembers.actorType, 'user'),+ eq(channelMembers.status, 'active'),+ ),+ )+ .limit(2);+ return people.length > 1;+};++/** Opens (or joins) the Thread under `rootMessageId` and moves the job into it. */+const openReplyThread = async (+ tx: Transaction,+ channelId: string,+ job: typeof channelJobs.$inferSelect,+ rootMessageId: string,+ title: string,+) => {+ // Follow-ups deferred behind this answer move with it: they must read it to stay silent.+ const deferred = await tx+ .select({ id: channelJobs.id, memberId: channelJobs.memberId })+ .from(channelJobs)+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ eq(channelJobs.messageId, job.messageId),+ eq(channelJobs.status, 'queued'),+ isNull(channelJobs.threadId),+ sql`${channelJobs.wake}->>'afterMemberId' = ${job.memberId}`,+ ),+ );+ const candidates = [+ ...new Set([job.requesterMemberId, job.memberId, ...deferred.map(({ memberId }) => memberId)]),+ ];+ // A member who has left since the request no longer follows anything.+ const followers = (+ await tx+ .select({ id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channelId),+ eq(channelMembers.status, 'active'),+ inArray(channelMembers.id, candidates),+ ),+ )+ ).map(({ id }) => id);+ const thread = await createChannelThread(tx, channelId, {+ followerMemberIds: followers,+ rootMessageId,+ });+ // A Thread already open under the request (another Agent's answer, or one someone branched)+ // keeps its name, and gains whoever answers in it.+ await followThread(tx, thread, followers);+ if (!thread.metadata?.title) await nameThread(tx, thread.id, title);+ await tx+ .update(channelJobs)+ .set({ threadId: thread.id })+ .where(inArray(channelJobs.id, [job.id, ...deferred.map(({ id }) => id)]));+ return thread.id;+};+const hasArchivedThread = async (tx: Transaction, channelId: string, rootMessageId: string) => {const [thread] = await tx.select({ status: channelThreads.status })diff --git a/packages/database/src/repositories/channel/openingLayout.ts b/packages/database/src/repositories/channel/openingLayout.tsnew file mode 100644index 00000000000..0944df43b5e--- /dev/null+++ b/packages/database/src/repositories/channel/openingLayout.ts@@ -0,0 +1,41 @@+/**+ * Where an Agent's opening puts its acknowledgement and the Thread its reply moves into.+ *+ * - `inline`: no Thread. The acknowledgement answers the request where it was asked, and the reply+ * follows it there.+ * - `underRequest`: the Thread opens under the request and the acknowledgement is its first reply,+ * so a shared timeline gains only the Thread's entry.+ * - `underAck`: the acknowledgement answers the request where it was asked and the Thread opens+ * under it, so the person sees the reply start and where it went. Without an acknowledgement+ * the Thread opens under the request.+ */+export type OpeningLayout = 'inline' | 'underAck' | 'underRequest';++/** What the layout depends on, gathered before anything is posted. */+export interface OpeningFacts {+ /** The opener posts an acknowledgement. */+ acknowledges: boolean;+ /** The request is already inside a Thread, so the reply cannot move into a new one. */+ inThread: boolean;+ /** An archived Thread sits under the request: it takes no new work. */+ requestHasArchivedThread: boolean;+ /** More than one person is in the Channel, so its main timeline is shared. */+ sharedTimeline: boolean;+ /** The opener named a Thread for the reply. */+ wantsThread: boolean;+}++/** The order rules apply in; the first that matches decides the layout. */+const OPENING_RULES: { layout: OpeningLayout; when: (facts: OpeningFacts) => boolean }[] = [+ // The opener judged the reply short, or it already runs in a Thread.+ { layout: 'inline', when: (f) => !f.wantsThread || f.inThread },+ // A shared timeline stays quiet: everything about the reply goes in the request's Thread.+ { layout: 'underRequest', when: (f) => f.sharedTimeline && !f.requestHasArchivedThread },+ // Nothing new to hang a Thread under, and the request's Thread is archived.+ { layout: 'inline', when: (f) => !f.acknowledges && f.requestHasArchivedThread },+ // A direct conversation, or a group whose request already has an archived Thread.+ { layout: 'underAck', when: () => true },+];++export const chooseOpeningLayout = (facts: OpeningFacts): OpeningLayout =>+ OPENING_RULES.find(({ when }) => when(facts))!.layout;