🤯 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): show an Agent reply's external works as cards (#22887)
Arvin Xudfd2a38c23bf
diff --git a/packages/database/src/repositories/channel/__tests__/replyWorks.test.ts b/packages/database/src/repositories/channel/__tests__/replyWorks.test.tsnew file mode 100644index 00000000000..0887d96446c--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/replyWorks.test.ts@@ -0,0 +1,231 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { WorkModel } from '../../../models/work';+import { works, workVersions } from '../../../schemas';+import { ChannelExecutionRepository } from '..';+import { createChannelFixture, jobById, jobsOf, lease } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-reply-works');+const execution = new ChannelExecutionRepository(db);+beforeEach(fixture.setup);+afterEach(fixture.cleanup);++/** A member asks the Agent and its reply is published from the member's own run. */+const publishedReply = async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Agent');+ const request = await team.asMember.send(team.channel.id, {+ content: 'Open a PR',+ mentions: [agent.id],+ requestKey: 'question',+ routing: 'fallback',+ });+ const [job] = await jobsOf(db, request.id);+ await execution.claim(team.channel.id, job.id, lease);+ await execution.accepted(team.channel.id, job.id);+ await execution.saveDraft(team.channel.id, job.id, 'Opened it');+ await execution.publish(team.channel.id, job.id);+ await execution.releaseWriter(team.channel.id, job.id);+ const { operationId } = await jobById(db, job.id);+ const reply = async (repo: typeof team.asOwner, threadId?: string) => {+ const view = await repo.detail(team.channel.id, threadId ? { threadId } : undefined);+ return threadId+ ? view.rootMessage!+ : view.messages.find((message) => message.routingStatus === 'reply')!;+ };+ return { ...team, operationId: operationId!, reply, request };+};++interface WorkFixture {+ at?: Date;+ cost?: number;+ metadata?: Record<string, unknown>;+ ownerId?: string;+ resourceType?: string;+ rootOperationId: string;+ share?: boolean;+ tokens?: number;+ trashed?: boolean;+ type?: 'document' | 'external';+ url?: string | null;+}++const addWork = async ({+ at,+ cost,+ metadata,+ ownerId = fixture.memberId,+ resourceType = 'github_pull_request',+ rootOperationId,+ share = false,+ trashed = false,+ tokens,+ type = 'external',+ url = 'https://github.com/lobehub/lobehub/pull/1',+}: WorkFixture) => {+ const [work] = await db+ .insert(works)+ .values({+ description: 'Adds the cards',+ identifier: 'lobehub/lobehub#1',+ isDeleted: trashed,+ updatedAt: at,+ metadata: share+ ? ({+ agentShare: { shareId: 's', topicId: 't', visitorUserId: 'v' },+ } as typeof works.$inferInsert.metadata)+ : null,+ resourceId: `${resourceType}:${Math.random()}`,+ resourceType: resourceType as typeof works.$inferInsert.resourceType,+ status: 'open',+ title: 'Show works in channels',+ toolIdentifier: 'github',+ toolName: 'createPullRequest',+ type,+ url,+ userId: ownerId,+ visibility: 'private',+ workspaceId: fixture.workspaceId,+ })+ .returning();+ const [version] = await db+ .insert(workVersions)+ .values({+ changeType: 'created',+ createdAt: at,+ cumulativeCost: cost ?? null,+ cumulativeUsage:+ tokens === undefined+ ? null+ : { capturedAt: '2026-11-12T00:00:00Z', usage: { llm: { tokens: { total: tokens } } } },+ metadata: metadata as typeof workVersions.$inferInsert.metadata,+ rootOperationId,+ toolIdentifier: 'github',+ toolName: 'createPullRequest',+ url,+ version: 1,+ workId: work.id,+ })+ .returning();+ await db.update(works).set({ currentVersionId: version.id }).where(eq(works.id, work.id));+ return work;+};++describe('Channel reply works', () => {+ it('shows every member the conversation summaries of the reply run, without its ids', async () => {+ const state = await publishedReply();+ const work = await addWork({+ cost: 0.42,+ metadata: { baseBranch: 'canary', headBranch: 'feat/cards' },+ rootOperationId: state.operationId,+ tokens: 1200,+ });+ // A later run of the requester's on the same PR: the card totals it, as the conversation does.+ await db.insert(workVersions).values({+ changeType: 'updated',+ cumulativeCost: 0.1,+ rootOperationId: 'op_later_run',+ toolIdentifier: 'github',+ toolName: 'updatePullRequest',+ version: 2,+ workId: work.id,+ });+ const [conversation] = (+ await new WorkModel(db, fixture.memberId, fixture.workspaceId).listSummariesByRootOperations({+ rootOperationIds: [state.operationId],+ })+ )[state.operationId];++ for (const repo of [state.asMember, state.asOwner]) {+ const [card] = (await state.reply(repo)).works!;+ expect(card).toEqual({+ ...conversation,+ currentVersionId: null,+ event: {+ ...conversation.event,+ id: '',+ messageId: null,+ rootOperationId: null,+ toolCallId: null,+ },+ id: 'https://github.com/lobehub/lobehub/pull/1',+ originAgentId: null,+ originThreadId: null,+ originTopicId: null,+ userId: '',+ version: null,+ workspaceId: null,+ });+ expect(card).toMatchObject({+ event: {+ cumulativeUsage: { usage: { llm: { tokens: { total: 1200 } } } },+ metadata: { baseBranch: 'canary', headBranch: 'feat/cards' },+ },+ identifier: 'lobehub/lobehub#1',+ title: 'Show works in channels',+ totalCost: 0.52,+ });+ const payload = JSON.stringify(card);+ expect(payload).not.toContain(work.id);+ expect(payload).not.toContain(state.operationId);+ expect(payload).not.toContain(fixture.memberId);+ }+ });++ it('keeps internal, unlinked, shared, trashed and foreign Works out', async () => {+ const state = await publishedReply();+ await addWork({+ resourceType: 'document',+ rootOperationId: state.operationId,+ type: 'document',+ });+ await addWork({ rootOperationId: state.operationId, url: null });+ await addWork({ rootOperationId: state.operationId, share: true });+ await addWork({ rootOperationId: state.operationId, trashed: true });+ await addWork({ ownerId: fixture.ownerId, rootOperationId: state.operationId });+ await addWork({ rootOperationId: 'op_another_run' });++ expect((await state.reply(state.asOwner)).works).toEqual([]);+ });++ it('lists the newest Works first and leaves requests without any', async () => {+ const state = await publishedReply();+ await addWork({+ at: new Date('2026-11-12T10:00:00Z'),+ rootOperationId: state.operationId,+ url: 'https://github.com/a/b/pull/1',+ });+ await addWork({+ at: new Date('2026-11-12T10:05:00Z'),+ resourceType: 'linear_issue',+ rootOperationId: state.operationId,+ url: 'https://linear.app/x/issue/ENG-1',+ });++ const reply = await state.reply(state.asOwner);+ expect(reply.works?.map((card) => card.url)).toEqual([+ 'https://linear.app/x/issue/ENG-1',+ 'https://github.com/a/b/pull/1',+ ]);+ expect(reply.works?.[0]).toMatchObject({ event: { cumulativeUsage: null }, totalCost: null });+ const request = (await state.asOwner.detail(state.channel.id)).messages.find(+ (message) => message.id === state.request.id,+ )!;+ expect(request.works).toEqual([]);+ });++ it('carries the Works on a thread root', async () => {+ const state = await publishedReply();+ await addWork({ rootOperationId: state.operationId });+ const reply = await state.reply(state.asOwner);+ const thread = await state.asOwner.createThread(state.channel.id, { rootMessageId: reply.id });++ expect((await state.reply(state.asOwner, thread.id)).works).toEqual([+ expect.objectContaining({ url: 'https://github.com/lobehub/lobehub/pull/1' }),+ ]);+ });+});diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.tsindex 2c186d910da..7f78357b182 100644--- a/packages/database/src/repositories/channel/view.ts+++ b/packages/database/src/repositories/channel/view.ts@@ -16,6 +16,7 @@ import { notTrashed } from '../../utils/softDelete';import { fileIdsByMessage } from './attachments';import { activeMembers } from './delivery';import { ChannelError } from './error';+import { externalWorksByMessage } from './works';const publicMessageColumns = {...getTableColumns(channelMessages),@@ -218,14 +219,13 @@ export const readChannelView = async (...page.map((message) => message.id),...(rootMessage ? [rootMessage.id] : []),]);- const sourceTopics = await sourceTopicsByMessage(- tx,- channelId,- [...page, ...(rootMessage ? [rootMessage] : [])].flatMap((message) =>- message.routingStatus === 'reply' ? [message.id] : [],- ),- viewerUserId,+ const replyIds = [...page, ...(rootMessage ? [rootMessage] : [])].flatMap((message) =>+ message.routingStatus === 'reply' ? [message.id] : [],);+ const [sourceTopics, works] = await Promise.all([+ sourceTopicsByMessage(tx, channelId, replyIds, viewerUserId),+ externalWorksByMessage(tx, channelId, replyIds),+ ]);const ids = [...new Set([...files.values()].flat())];const attachments = ids.length? await tx@@ -250,6 +250,7 @@ export const readChannelView = async (...publicMessage(rootMessage, files.get(rootMessage.id) ?? []),sourceTopicId: sourceTopics.get(rootMessage.id)?.id ?? null,sourceTopicTitle: sourceTopics.get(rootMessage.id)?.title ?? null,+ works: works.get(rootMessage.id) ?? [],replyTo: rootMessage.replyToId ? (quotes.get(rootMessage.replyToId) ?? null) : null,}: null,@@ -257,6 +258,7 @@ export const readChannelView = async (...publicMessage(message, files.get(message.id) ?? []),sourceTopicId: sourceTopics.get(message.id)?.id ?? null,sourceTopicTitle: sourceTopics.get(message.id)?.title ?? null,+ works: works.get(message.id) ?? [],replyTo: message.replyToId ? (quotes.get(message.replyToId) ?? null) : null,})),};diff --git a/packages/database/src/repositories/channel/works.ts b/packages/database/src/repositories/channel/works.tsnew file mode 100644index 00000000000..1f3d696bd66--- /dev/null+++ b/packages/database/src/repositories/channel/works.ts@@ -0,0 +1,96 @@+import type { ExternalWorkSummaryItem, WorkSummaryItem } from '@lobechat/types';+import { and, eq, inArray, isNotNull } from 'drizzle-orm';+import pMap from 'p-map';++import { WorkModel } from '../../models/work';+import { channelJobs, channelMembers, channels } from '../../schemas';+import type { Transaction } from '../../type';++const isLinkedExternalWork = (item: WorkSummaryItem): item is ExternalWorkSummaryItem =>+ item.type === 'external' && !!item.url;++/**+ * A summary as other members see it: what the card draws, without the ids that tie it to the+ * requester's Work, conversation and run. The URL keys the card in place of the Work id.+ */+const publicSummary = (item: ExternalWorkSummaryItem): ExternalWorkSummaryItem => ({+ ...item,+ currentVersionId: null,+ event: { ...item.event, id: '', messageId: null, rootOperationId: null, toolCallId: null },+ id: item.url!,+ originAgentId: null,+ originThreadId: null,+ originTopicId: null,+ userId: '',+ version: null,+ workspaceId: null,+});++/**+ * The external Works (GitHub, Linear, ...) each published reply's run touched, as the work cards+ * the requester's own conversation shows under that run: the same+ * `WorkModel.listSummariesByRootOperations` read, as the requester, keyed by the job's operation.+ *+ * Every member sees them: a reply already shows what it did, and these resources live outside+ * LobeHub behind their own URL. Internal Works (documents, canvases, files, tasks) stay with the+ * requester, as do the ids that link a card to the requester's Work, topic and run.+ */+export const externalWorksByMessage = async (+ tx: Transaction,+ channelId: string,+ messageIds: string[],+): Promise<Map<string, ExternalWorkSummaryItem[]>> => {+ const result = new Map<string, ExternalWorkSummaryItem[]>();+ if (!messageIds.length) return result;++ const jobs = await tx+ .select({+ messageId: channelJobs.publishedMessageId,+ operationId: channelJobs.operationId,+ requesterUserId: channelMembers.userId,+ workspaceId: channels.workspaceId,+ })+ .from(channelJobs)+ .innerJoin(channels, eq(channels.id, channelJobs.channelId))+ .innerJoin(+ channelMembers,+ and(+ eq(channelMembers.channelId, channelJobs.channelId),+ eq(channelMembers.id, channelJobs.requesterMemberId),+ ),+ )+ .where(+ and(+ eq(channelJobs.channelId, channelId),+ inArray(channelJobs.publishedMessageId, messageIds),+ isNotNull(channelJobs.operationId),+ isNotNull(channelMembers.userId),+ ),+ );+ if (!jobs.length) return result;++ // The run is the requester's, so its Works are read the way their own conversation reads them.+ const byRequester = new Map<string, typeof jobs>();+ for (const job of jobs)+ byRequester.set(job.requesterUserId!, [...(byRequester.get(job.requesterUserId!) ?? []), job]);+ await pMap(+ [...byRequester],+ async ([userId, requesterJobs]) => {+ const summaries = await new WorkModel(+ tx,+ userId,+ requesterJobs[0].workspaceId ?? undefined,+ ).listSummariesByRootOperations({+ rootOperationIds: requesterJobs.map((job) => job.operationId!),+ });+ for (const job of requesterJobs) {+ const cards = (summaries[job.operationId!] ?? [])+ .filter(isLinkedExternalWork)+ .map(publicSummary);+ if (cards.length) result.set(job.messageId!, cards);+ }+ },+ { concurrency: 5 },+ );+ return result;+};diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.tsindex a34d2979d81..44c57a24b26 100644--- a/packages/types/src/channel.ts+++ b/packages/types/src/channel.ts@@ -2,6 +2,7 @@ import type { LobeAgentAgencyConfig, LobeAgentConfig, RemoteHeterogeneousAgentTyimport { LocalExecutionHeterogeneousAgentTypeSchema } from './agent/heterogeneousAgent';import { getWorkingDirEffectivePath } from './device';import type { BotWakeKind } from './signal';+import type { ExternalWorkSummaryItem } from './work';/*** Channel: a shared conversation where people and Agents talk together.@@ -411,6 +412,11 @@ export interface ChannelPublicMessage {sourceTopicTitle?: string | null;threadId: string | null;userId: string | null;+ /**+ * External Works a reply's run touched: the conversation's work summaries, for every member,+ * without the ids that link them to the requester's Work, topic and run. Empty on requests.+ */+ works?: ExternalWorkSummaryItem[];}export interface ChannelPublicJob {diff --git a/src/features/Channels/ChannelMessage.test.tsx b/src/features/Channels/ChannelMessage.test.tsxindex 7474f34db4b..27d1de1606c 100644--- a/src/features/Channels/ChannelMessage.test.tsx+++ b/src/features/Channels/ChannelMessage.test.tsx@@ -1,7 +1,7 @@/*** @vitest-environment happy-dom*/-import type { ChannelDetail, ChannelPublicMessage } from '@lobechat/types';+import type { ChannelDetail, ChannelPublicMessage, ExternalWorkSummaryItem } from '@lobechat/types';import { fireEvent, render, screen } from '@testing-library/react';import { act, createElement, type ReactNode } from 'react';import { describe, expect, it, vi } from 'vitest';@@ -181,3 +181,61 @@ describe('ChannelMessage collapse', () => {expect(screen.getByText('message.expand')).toBeTruthy();});});++describe('ChannelMessage works', () => {+ const url = 'https://github.com/lobehub/lobehub/pull/1';+ const work = {+ description: 'Adds the cards',+ event: {+ cumulativeCost: 0.42,+ cumulativeUsage: null,+ metadata: { baseBranch: 'canary', headBranch: 'feat/cards' },+ },+ id: url,+ identifier: 'lobehub/lobehub#1',+ resourceDeleted: false,+ resourceType: 'github_pull_request',+ status: 'open',+ title: 'Show works in channels',+ totalCost: 0.42,+ type: 'external',+ url,+ } as unknown as ExternalWorkSummaryItem;++ it('shows a reply’s external Works as cards that open their link', () => {+ const open = vi.spyOn(window, 'open').mockReturnValue(null);+ render(+ <ChannelMessage+ detail={detail}+ message={{+ ...message({ avatar: null, id: 'agt_1', name: 'Sanjo', type: 'agent' }),+ content: 'Opened it',+ works: [work],+ }}+ />,+ );++ expect(screen.getByText('Show works in channels')).toBeTruthy();+ expect(screen.getByText('lobehub/lobehub#1')).toBeTruthy();+ expect(screen.getByText('feat/cards')).toBeTruthy();+ expect(screen.getByText('0.42')).toBeTruthy();++ fireEvent.click(screen.getByText('Show works in channels'));+ expect(open).toHaveBeenCalledWith(url, '_blank', 'noopener,noreferrer');+ open.mockRestore();+ });++ it('renders no cards without Works', () => {+ render(+ <ChannelMessage+ detail={detail}+ message={{+ ...message({ avatar: null, id: 'agt_1', name: 'Sanjo', type: 'agent' }),+ works: [],+ }}+ />,+ );++ expect(screen.queryByText('Show works in channels')).toBeNull();+ });+});diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsxindex 9933f7061a7..4f11bdd89de 100644--- a/src/features/Channels/ChannelMessage.tsx+++ b/src/features/Channels/ChannelMessage.tsx@@ -41,6 +41,7 @@ import { channelMessageTime, channelTimeFormatters } from './messagePresentationimport { MessageFailureMark, MessageRoutingStatus } from './MessageReceipts';import { showsReplyQuote } from './replyQuote';import type { ReplyTopic } from './ReplyTopicPanel';+import { ReplyWorks } from './ReplyWorks';import { styles } from './styles';import type { ChannelThreadDraft } from './threadDraft';import type { ChannelReplyTarget } from './useReplyTarget';@@ -314,6 +315,7 @@ export const ChannelMessage = ({) : (<MessageText content={message.content} names={mentionNames} />))}+ {!!message.works?.length && <ReplyWorks works={message.works} />}</Flexbox>}titleAddon={diff --git a/src/features/Channels/ReplyWorks.tsx b/src/features/Channels/ReplyWorks.tsxnew file mode 100644index 00000000000..dd937651db8--- /dev/null+++ b/src/features/Channels/ReplyWorks.tsx@@ -0,0 +1,14 @@+import type { WorkSummaryItem } from '@lobechat/types';++import { MessageWorkList } from '@/features/Conversation/Messages/MessageWorks';+import { isSafeExternalUrl } from '@/features/Work/descriptors';++/** A channel has no Working Sidebar or chat portal: a card just opens its link. */+const openLink = (item: WorkSummaryItem) => {+ if (isSafeExternalUrl(item.url)) window.open(item.url, '_blank', 'noopener,noreferrer');+};++/** The external Works an Agent reply's run touched, as the conversation shows them. */+export const ReplyWorks = ({ works }: { works: WorkSummaryItem[] }) => (+ <MessageWorkList items={works} onOpen={openLink} />+);