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): summarize responder topic titles like the bot flow (#22688)

Arvin Xube2791d890b9
diff --git a/apps/server/src/services/channel/ChannelCoordinator.test.ts b/apps/server/src/services/channel/ChannelCoordinator.test.ts
index f7a625cb864..95588397056 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.test.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.test.ts
@@ -6,6 +6,7 @@ import { ChannelCoordinator } from './ChannelCoordinator';
const { executions, executeToolCall, interruptTask } = vi.hoisted(() => ({
interruptTask: vi.fn().mockResolvedValue({ success: true }),
executions: {
+ input: vi.fn(),
publish: vi.fn(),
releaseWriter: vi.fn(),
retireReservation: vi.fn().mockResolvedValue(false),
@@ -13,6 +14,22 @@ const { executions, executeToolCall, interruptTask } = vi.hoisted(() => ({
},
executeToolCall: vi.fn(),
}));
+const { findTopic, generateTopicTitle, updateTopic } = vi.hoisted(() => ({
+ findTopic: vi.fn(),
+ generateTopicTitle: vi.fn(),
+ updateTopic: vi.fn(),
+}));
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: class {
+ findById = findTopic;
+ update = updateTopic;
+ },
+}));
+vi.mock('@/server/services/systemAgent', () => ({
+ SystemAgentService: class {
+ generateTopicTitle = generateTopicTitle;
+ },
+}));
vi.mock('@/database/repositories/channel', () => ({
ChannelExecutionRepository: class {
constructor() {
@@ -44,6 +61,7 @@ describe('Channel completion physical writer confirmation', () => {
runtime = 'codex',
leaseOwner: string | null = null,
status = 'done',
+ topicId: string | null = null,
) => {
const job = {
channelId: 'channel',
@@ -53,6 +71,7 @@ describe('Channel completion physical writer confirmation', () => {
manifest: {},
operationId: 'op',
publicationRevoked,
+ topicId,
writerHeld: true,
};
const operation = { id: 'op', status, userId: 'user', workspaceId: null };
@@ -87,6 +106,36 @@ describe('Channel completion physical writer confirmation', () => {
},
);
+ it('names an untitled topic from the request and the published reply', async () => {
+ executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
+ executions.input.mockResolvedValue([{ content: 'What can you do?' }]);
+ findTopic.mockResolvedValue({ title: null });
+ generateTopicTitle.mockResolvedValue('Assistant abilities');
+
+ await coordinator(false, 'codex', null, 'done', 'topic').complete('channel', 'job', 'op');
+
+ await vi.waitFor(() =>
+ expect(updateTopic).toHaveBeenCalledWith('topic', { title: 'Assistant abilities' }),
+ );
+ expect(generateTopicTitle).toHaveBeenCalledWith({
+ lastAssistantContent: 'Final reply',
+ topicId: 'topic',
+ userPrompt: 'What can you do?',
+ });
+ });
+
+ it('keeps the title of a topic that already has one', async () => {
+ executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
+ findTopic.mockResolvedValue({ title: 'Existing' });
+
+ await coordinator(false, 'codex', null, 'done', 'topic').complete('channel', 'job', 'op');
+
+ await vi.waitFor(() => expect(findTopic).toHaveBeenCalledWith('topic'));
+ await Promise.resolve();
+ expect(generateTopicTitle).not.toHaveBeenCalled();
+ expect(updateTopic).not.toHaveBeenCalled();
+ });
+
it('releases a completed writer only after the device confirms termination', async () => {
executeToolCall.mockResolvedValue({ success: true, state: { exited: true } });
await coordinator().complete('channel', 'job', 'op');
diff --git a/apps/server/src/services/channel/ChannelCoordinator.ts b/apps/server/src/services/channel/ChannelCoordinator.ts
index 38b96e0d51d..f3ae7b4b36e 100644
--- a/apps/server/src/services/channel/ChannelCoordinator.ts
+++ b/apps/server/src/services/channel/ChannelCoordinator.ts
@@ -10,6 +10,7 @@ import pMap from 'p-map';
import { getServerDB } from '@/database/core/db-adaptor';
import { AgentOperationModel } from '@/database/models/agentOperation';
import { MessageModel } from '@/database/models/message';
+import { TopicModel } from '@/database/models/topic';
import type { ChannelClaim } from '@/database/repositories/channel';
import { ChannelExecutionRepository } from '@/database/repositories/channel';
import { agentOperations, channelJobs, channelMembers, channels } from '@/database/schemas';
@@ -21,6 +22,7 @@ import { detectNoReply } from '@/server/services/conversationWake/noReply';
import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
import { isQueueAgentRuntimeEnabled } from '@/server/services/queue/impls';
+import { SystemAgentService } from '@/server/services/systemAgent';
import { resolveChannelAttachments } from './attachments';
import { ChannelRoutingService } from './ChannelRoutingService';
@@ -262,6 +264,7 @@ export class ChannelCoordinator {
await this.stopWriters([job]);
return;
}
+ let reply = job.draft;
if (job.draft === null) {
if (!operation.userId || !job.topicId) return;
const final = await new MessageModel(
@@ -287,10 +290,17 @@ export class ChannelCoordinator {
}
await this.executions.accepted(channelId, jobId);
await this.executions.saveDraft(channelId, jobId, content);
+ reply = content;
}
await this.executions.publish(channelId, jobId);
await this.stopWriters([job]);
await notifyChannel(this.db, channelId);
+ this.summarizeTopicTitle(channelId, jobId, {
+ lastAssistantContent: reply,
+ topicId: job.topicId,
+ userId: operation.userId,
+ workspaceId: operation.workspaceId,
+ });
} else if (['error', 'interrupted', 'abandoned'].includes(operation.status)) {
await this.executions.fail(channelId, jobId, {
message: 'Agent execution ended without a reply',
@@ -300,6 +310,54 @@ export class ChannelCoordinator {
}
};
+ /**
+ * Names a responder's topic after its first published reply, as the bot callback does. The
+ * title comes from the request itself: the topic's user message is the wrapped Channel prompt.
+ * Best-effort, so it never affects delivery.
+ */
+ private summarizeTopicTitle(
+ channelId: string,
+ jobId: string,
+ {
+ lastAssistantContent,
+ topicId,
+ userId,
+ workspaceId,
+ }: {
+ lastAssistantContent: string | null;
+ topicId: string | null;
+ userId: string | null;
+ workspaceId: string | null;
+ },
+ ): void {
+ if (!lastAssistantContent || !topicId || !userId) return;
+
+ const topicModel = new TopicModel(this.db, userId, workspaceId ?? undefined);
+ topicModel
+ .findById(topicId)
+ .then(async (topic) => {
+ if (topic?.title) return;
+
+ const input = await this.executions.input(channelId, jobId);
+ const userPrompt = input.map((message) => message.content).join('\n');
+ if (!userPrompt) return;
+
+ const title = await new SystemAgentService(
+ this.db,
+ userId,
+ workspaceId ?? undefined,
+ ).generateTopicTitle({ lastAssistantContent, topicId, userPrompt });
+ if (!title) return;
+
+ await topicModel.update(topicId, { title });
+ // Viewers read the title from the Channel view, which was sent before it existed.
+ await notifyChannel(this.db, channelId);
+ })
+ .catch((error) => {
+ console.error('[channel:summarizeTopicTitle]', error);
+ });
+ }
+
stopWriters = async (
jobs: Array<{ channelId: string; id: string; operationId: string | null }>,
) => {
diff --git a/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts b/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts
index 455172589b6..c0cde2cc147 100644
--- a/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts
+++ b/packages/database/src/repositories/channel/__tests__/sourceTopic.test.ts
@@ -43,6 +43,14 @@ describe('Channel reply source topic', () => {
expect((await state.reply(state.asMember)).sourceTopicId).toBe(state.topicId);
});
+ it('carries the generated topic title for the member who ran it', async () => {
+ const state = await publishedReply();
+ await db.update(topics).set({ title: 'Named' }).where(eq(topics.id, state.topicId));
+
+ expect((await state.reply(state.asMember)).sourceTopicTitle).toBe('Named');
+ expect((await state.reply(state.asOwner)).sourceTopicTitle).toBeNull();
+ });
+
it('hides the topic from other members and on requests', async () => {
const state = await publishedReply();
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index f8bad59a4bc..6c4651a636e 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -70,9 +70,14 @@ const sourceTopicsByMessage = async (
messageIds: string[],
viewerUserId: string | undefined,
) => {
- if (!viewerUserId || !messageIds.length) return new Map<string, string>();
+ if (!viewerUserId || !messageIds.length)
+ return new Map<string, { id: string; title: string | null }>();
const rows = await tx
- .select({ messageId: channelJobs.publishedMessageId, topicId: topics.id })
+ .select({
+ messageId: channelJobs.publishedMessageId,
+ title: topics.title,
+ topicId: topics.id,
+ })
.from(channelJobs)
.innerJoin(topics, eq(topics.id, channelJobs.topicId))
.where(
@@ -83,7 +88,7 @@ const sourceTopicsByMessage = async (
notTrashed(topics.isDeleted),
),
);
- return new Map(rows.map((row) => [row.messageId!, row.topicId]));
+ return new Map(rows.map((row) => [row.messageId!, { id: row.topicId, title: row.title }]));
};
export const readChannelView = async (
@@ -242,13 +247,15 @@ export const readChannelView = async (
rootMessage: rootMessage
? {
...publicMessage(rootMessage, files.get(rootMessage.id) ?? []),
- sourceTopicId: sourceTopics.get(rootMessage.id) ?? null,
+ sourceTopicId: sourceTopics.get(rootMessage.id)?.id ?? null,
+ sourceTopicTitle: sourceTopics.get(rootMessage.id)?.title ?? null,
replyTo: rootMessage.replyToId ? (quotes.get(rootMessage.replyToId) ?? null) : null,
}
: null,
messages: page.map((message) => ({
...publicMessage(message, files.get(message.id) ?? []),
- sourceTopicId: sourceTopics.get(message.id) ?? null,
+ sourceTopicId: sourceTopics.get(message.id)?.id ?? null,
+ sourceTopicTitle: sourceTopics.get(message.id)?.title ?? null,
replyTo: message.replyToId ? (quotes.get(message.replyToId) ?? null) : null,
})),
};
diff --git a/packages/types/src/channel.ts b/packages/types/src/channel.ts
index 59af797b84b..3899dcef024 100644
--- a/packages/types/src/channel.ts
+++ b/packages/types/src/channel.ts
@@ -356,6 +356,7 @@ export interface ChannelPublicMessage {
sequence: number;
/** The Agent topic behind a reply, only when the viewer ran it (owns that topic). */
sourceTopicId?: string | null;
+ sourceTopicTitle?: string | null;
threadId: string | null;
userId: string | null;
}
diff --git a/src/features/Channels/ChannelMessage.tsx b/src/features/Channels/ChannelMessage.tsx
index 8c519cf7181..cebf09465fe 100644
--- a/src/features/Channels/ChannelMessage.tsx
+++ b/src/features/Channels/ChannelMessage.tsx
@@ -157,6 +157,7 @@ export const ChannelMessage = ({
agentId: agentAuthorId,
avatar: message.author.avatar,
name: message.author.name || t('unnamedAgent'),
+ title: message.sourceTopicTitle,
topicId: sourceTopicId,
}),
},
diff --git a/src/features/Channels/ReplyTopicPanel.tsx b/src/features/Channels/ReplyTopicPanel.tsx
index 3d25f9f3166..8f45ed9f6be 100644
--- a/src/features/Channels/ReplyTopicPanel.tsx
+++ b/src/features/Channels/ReplyTopicPanel.tsx
@@ -26,6 +26,7 @@ export interface ReplyTopic {
agentId: string;
avatar: string | null;
name: string;
+ title?: string | null;
topicId: string;
}
@@ -116,7 +117,7 @@ export function ReplyTopicPanel({
size={20}
/>
<Text ellipsis fontSize={14}>
- {t('topic.titleNamed', { name: lastTopic.name })}
+ {lastTopic.title || t('topic.titleNamed', { name: lastTopic.name })}
</Text>
</Flexbox>
)