🤯 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): carry threads' replies at work on the main timeline view (#23106)
Arvin Xu3d8738189375
diff --git a/packages/database/src/repositories/channel/__tests__/view.test.ts b/packages/database/src/repositories/channel/__tests__/view.test.tsindex 72559544bea..2f06e76f77b 100644--- a/packages/database/src/repositories/channel/__tests__/view.test.ts+++ b/packages/database/src/repositories/channel/__tests__/view.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';-import { channelJobs, channelMembers } from '../../../schemas';+import { channelJobs, channelMembers, channelMessages } from '../../../schemas';import { ChannelExecutionRepository, ChannelRepository } from '..';import { createChannelFixture, jobsOf, lease } from './testUtils';@@ -117,6 +117,89 @@ describe('Channel public view', () => {).rejects.toMatchObject({ code: 'BAD_REQUEST' });});+ it("carries a thread's replies at work on the main timeline, and only until they settle", async () => {+ const { asOwner, channel } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(channel.id, 'Researcher');+ const root = await asOwner.send(channel.id, {+ content: 'Root',+ requestKey: 'root',+ routing: 'fallback',+ });+ const thread = await asOwner.createThread(channel.id, { rootMessageId: root.id });+ const request = await asOwner.send(channel.id, {+ content: 'Dig into it',+ mentions: [agent.id],+ requestKey: 'thread-work',+ routing: 'fallback',+ threadId: thread.id,+ });+ const [job] = await jobsOf(db, request.id);+ const setJob = (patch: Partial<typeof channelJobs.$inferInsert>) =>+ db.update(channelJobs).set(patch).where(eq(channelJobs.id, job.id));+ const threadJobsOnMain = async () =>+ (await asOwner.detail(channel.id)).jobs.filter((entry) => entry.threadId === thread.id);++ await setJob({ status: 'running', writerHeld: true });+ expect(await threadJobsOnMain()).toEqual([+ expect.objectContaining({ id: job.id, status: 'running', threadId: thread.id }),+ ]);++ // Stopping: no longer running, but still holding the writer.+ await setJob({ publicationRevoked: true, status: 'cancelled', writerHeld: true });+ expect((await threadJobsOnMain()).map((entry) => entry.id)).toEqual([job.id]);++ await setJob({ status: 'completed', writerHeld: false });+ expect(await threadJobsOnMain()).toEqual([]);+ expect(+ (await asOwner.detail(channel.id, { threadId: thread.id })).jobs.map((entry) => entry.id),+ ).toEqual([job.id]);+ });++ it("keeps the main conversation's own jobs however many thread jobs are at work", async () => {+ const { asOwner, channel, owner } = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(channel.id, 'Researcher');+ const main = await asOwner.send(channel.id, {+ content: 'Main request',+ mentions: [agent.id],+ requestKey: 'main-work',+ routing: 'fallback',+ });+ const [mainJob] = await jobsOf(db, main.id);+ await db+ .update(channelJobs)+ .set({ createdAt: new Date(Date.now() - 60_000), status: 'running', writerHeld: true })+ .where(eq(channelJobs.id, mainJob.id));+ const thread = await asOwner.createThread(channel.id, { rootMessageId: main.id });+ // More queued thread work than the main view's own job limit.+ const messages = await db+ .insert(channelMessages)+ .values(+ Array.from({ length: 210 }, (_, index) => ({+ channelId: channel.id,+ content: `Thread request ${index}`,+ requestKey: `flood-${index}`,+ routingStatus: 'routed' as const,+ sequence: 10_000 + index,+ threadId: thread.id,+ userId: fixture.ownerId,+ })),+ )+ .returning({ id: channelMessages.id });+ await db.insert(channelJobs).values(+ messages.map(({ id }) => ({+ channelId: channel.id,+ memberId: agent.id,+ messageId: id,+ requesterMemberId: owner.id,+ threadId: thread.id,+ })),+ );++ const { jobs } = await asOwner.detail(channel.id);+ expect(jobs.filter((job) => !job.threadId).map((job) => job.id)).toEqual([mainJob.id]);+ expect(jobs.filter((job) => job.threadId === thread.id).length).toBeLessThan(210);+ });+it('summarizes each thread under its root on the main timeline only', async () => {const { asOwner, channel } = await fixture.createTeamChannel();const root = await asOwner.send(channel.id, {diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 7d3d081a142..5b06ddd828c 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -1,5 +1,19 @@import { channelMessageReceipt, channelMessageVia } from '@lobechat/types';-import { and, asc, count, desc, eq, getTableColumns, inArray, isNull, lt, sql } from 'drizzle-orm';+import {+ and,+ asc,+ count,+ desc,+ eq,+ getTableColumns,+ inArray,+ isNotNull,+ isNull,+ lt,+ or,+ type SQL,+ sql,+} from 'drizzle-orm';import {agentOperations,@@ -172,6 +186,47 @@ const threadSummaries = async (tx: Transaction, channelId: string, threadIds: st);};+/** A job as the public view shows it; `requesterMemberId` is dropped by the repository. */+const publicJobColumns = {+ id: channelJobs.id,+ memberId: channelJobs.memberId,+ messageId: channelJobs.messageId,+ requesterMemberId: channelJobs.requesterMemberId,+ threadId: channelJobs.threadId,+ status: channelJobs.status,+ blockedCode: channelJobs.blockedCode,+ // Only a bounded diagnostic message crosses the public boundary, never the raw error.+ errorMessage: sql<string | null>`CASE WHEN ${channelJobs.status} = 'failed'+ THEN left(${agentOperations.error}->>'message', 2000) ELSE NULL END`,+ // The error's category, so a client can explain a known failure in the viewer's language.+ errorType: sql<string | null>`CASE WHEN ${channelJobs.status} = 'failed'+ THEN ${agentOperations.error}->>'type' ELSE NULL END`,+ // The device the reply runs on, waits for, or failed to reach: the claimed device, the+ // one a failed dispatch was routed to, or the Agent's own bound device.+ deviceId: sql<string | null>`COALESCE(+ ${channelJobs.deviceId},+ ${agentOperations.error}->'deviceRoute'->>'deviceId',+ ${channelJobs.executionConfig}->'agencyConfig'->>'boundDeviceId'+ )`,+ writerHeld: channelJobs.writerHeld,+ worktreeBranch: sql<string | null>`${channelJobs.executionConfig}->>'worktreeBranch'`,+ operationStatus: agentOperations.status,+ createdAt: channelJobs.createdAt,+ publicationRevoked: channelJobs.publicationRevoked,+};++/** At most this many of a main view's threads' jobs still at work ride along with its own. */+const THREAD_ACTIVE_JOB_LIMIT = 50;++const readJobs = (tx: Transaction, where: SQL | undefined, limit: number) =>+ tx+ .select(publicJobColumns)+ .from(channelJobs)+ .leftJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))+ .where(where)+ .orderBy(desc(channelJobs.createdAt))+ .limit(limit);+export const readChannelView = async (tx: Transaction,channelId: string,@@ -179,7 +234,7 @@ export const readChannelView = async (viewerUserId?: string,) => {const limit = Math.max(1, Math.min(options.limit ?? 100, 100));- const [members, reversed, threads, jobs] = await Promise.all([+ const [members, reversed, threads, ownJobs, threadJobs] = await Promise.all([tx.select({actorType: channelMembers.actorType,@@ -226,47 +281,37 @@ export const readChannelView = async (.from(channelThreads).where(and(eq(channelThreads.channelId, channelId), notTrashed(channelThreads.isDeleted))).orderBy(asc(channelThreads.createdAt)),- tx- .select({- id: channelJobs.id,- memberId: channelJobs.memberId,- messageId: channelJobs.messageId,- requesterMemberId: channelJobs.requesterMemberId,- threadId: channelJobs.threadId,- status: channelJobs.status,- blockedCode: channelJobs.blockedCode,- // Only a bounded diagnostic message crosses the public boundary, never the raw error.- errorMessage: sql<string | null>`CASE WHEN ${channelJobs.status} = 'failed'- THEN left(${agentOperations.error}->>'message', 2000) ELSE NULL END`,- // The error's category, so a client can explain a known failure in the viewer's language.- errorType: sql<string | null>`CASE WHEN ${channelJobs.status} = 'failed'- THEN ${agentOperations.error}->>'type' ELSE NULL END`,- // The device the reply runs on, waits for, or failed to reach: the claimed device, the- // one a failed dispatch was routed to, or the Agent's own bound device.- deviceId: sql<string | null>`COALESCE(- ${channelJobs.deviceId},- ${agentOperations.error}->'deviceRoute'->>'deviceId',- ${channelJobs.executionConfig}->'agencyConfig'->>'boundDeviceId'- )`,- writerHeld: channelJobs.writerHeld,- worktreeBranch: sql<string | null>`${channelJobs.executionConfig}->>'worktreeBranch'`,- operationStatus: agentOperations.status,- createdAt: channelJobs.createdAt,- publicationRevoked: channelJobs.publicationRevoked,- })- .from(channelJobs)- .leftJoin(agentOperations, eq(agentOperations.id, channelJobs.operationId))- .where(- and(- eq(channelJobs.channelId, channelId),- options.threadId- ? eq(channelJobs.threadId, options.threadId)- : isNull(channelJobs.threadId),+ readJobs(+ tx,+ and(+ eq(channelJobs.channelId, channelId),+ options.threadId+ ? eq(channelJobs.threadId, options.threadId)+ : isNull(channelJobs.threadId),+ ),+ 200,+ ),+ // The main timeline also carries its threads' replies still at work, so a thread card and+ // the header can show an Agent working without loading every thread. Bounded on its own,+ // so busy threads never push the main conversation's own jobs out of its limit.+ options.threadId+ ? []+ : readJobs(+ tx,+ and(+ eq(channelJobs.channelId, channelId),+ isNotNull(channelJobs.threadId),+ or(+ inArray(channelJobs.status, ['queued', 'running']),+ eq(channelJobs.writerHeld, true),+ ),+ ),+ THREAD_ACTIVE_JOB_LIMIT,),- )- .orderBy(desc(channelJobs.createdAt))- .limit(200),]);+ const jobs = [...ownJobs, ...threadJobs].sort(+ (a, b) => b.createdAt.getTime() - a.createdAt.getTime(),+ );if (options.threadId && !threads.some((thread) => thread.id === options.threadId))throw new ChannelError('NOT_FOUND', 'Thread not found');const thread = threads.find((entry) => entry.id === options.threadId);diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex e8eff5ed233..88544d676d0 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -603,6 +603,10 @@ export interface ChannelDetail {attachments: Array<{ fileType: string; id: string; name: string; size: number; url: string }>;channel: ChannelListItem;hasMore: boolean;+ /**+ * The view's jobs. A main-timeline view also carries its threads' jobs still at work (queued,+ * running, or holding the writer); filter by `threadId` for one conversation's own.+ */jobs: ChannelPublicJob[];members: ChannelPublicMember[];messages: ChannelPublicMessage[];diff --git a/src/features/Channels/FailureIndicator.tsx b/src/features/Channels/FailureIndicator.tsxindex 2800ad3d9c2..cb59264c0e1 100644--- a/src/features/Channels/FailureIndicator.tsx+++ b/src/features/Channels/FailureIndicator.tsx@@ -4,7 +4,7 @@ import * as stylex from '@stylexjs/stylex';import { CircleAlert, LocateFixed } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { unresolvedFailures } from './jobStatus';+import { mainTimelineFailures } from './jobStatus';import type { ReplyEntry } from './MessageReceipts';import { ReplyDetail, replyEntries } from './MessageReceipts';import { statusStyles, toneStyles } from './styles';@@ -43,7 +43,7 @@ function FailureRow({ channelId, entry }: { channelId: string; entry: ReplyEntry*/export function FailureIndicator({ detail }: { detail: ChannelDetail }) {const { t } = useTranslation('channel');- const failures = unresolvedFailures(detail.jobs);+ const failures = mainTimelineFailures(detail.jobs);if (!failures.length) return null;const entries = replyEntries(detail, failures, t('unnamedAgent'));const label = t('failure.title', { count: failures.length });diff --git a/src/features/Channels/jobStatus.test.ts b/src/features/Channels/jobStatus.test.tsindex 01c88e2a0b9..97e988a8560 100644--- a/src/features/Channels/jobStatus.test.ts+++ b/src/features/Channels/jobStatus.test.ts@@ -6,6 +6,7 @@ import {channelJobTone,directAvatarState,hasReplyActivity,+ mainTimelineFailures,memberCurrentJob,memberJobStatus,replyActivityJobs,@@ -162,6 +163,19 @@ describe('Channel task tone', () => {});});+describe('mainTimelineFailures', () => {+ const job = (patch: Partial<ChannelPublicJob>) =>+ ({ memberId: 'a', publicationRevoked: false, threadId: null, ...patch }) as ChannelPublicJob;++ it('keeps a main failure while the same Agent works in a thread', () => {+ const jobs = [+ job({ id: 'thread-running', status: 'running', threadId: 'thr_1' }),+ job({ id: 'main-failed', status: 'failed' }),+ ];+ expect(mainTimelineFailures(jobs).map((entry) => entry.id)).toEqual(['main-failed']);+ });+});+describe('directAvatarState', () => {const job = (patch: Partial<ChannelPublicJob> = {}) =>({diff --git a/src/features/Channels/jobStatus.ts b/src/features/Channels/jobStatus.tsindex 02a26b7361e..46cc41b8567 100644--- a/src/features/Channels/jobStatus.ts+++ b/src/features/Channels/jobStatus.ts@@ -61,6 +61,13 @@ export const unresolvedFailures = <T extends ChannelReplyJob>(jobs: T[]) => {});};+/**+ * The header's failures: the main conversation's own. Its view also carries replies still at+ * work in threads, and one of those must not hide, then bring back, a main-timeline failure.+ */+export const mainTimelineFailures = <T extends ChannelReplyJob>(jobs: T[]) =>+ unresolvedFailures(jobs.filter((job) => !job.threadId));+/** What a member is busy with now: a running reply first, then the next queued one. */export const memberCurrentJob = <T extends ChannelReplyJob>(jobs: T[], memberId: string) => {const own = jobs.filter((job) => job.memberId === memberId);