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.

✨ feat(channel): search a Channel's messages, its Threads included (#23293)

Arvin Xub5032ef10e5d
diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.ts
index 387cee0a91c..e1091f37c57 100644
--- a/apps/server/src/routers/lambda/channel.ts
+++ b/apps/server/src/routers/lambda/channel.ts
@@ -229,6 +229,20 @@ export const channelRouter = router({
data: await ctx.channelService.detail(input.channelId, input),
success: true,
})),
+ /** Messages in a Channel and its Threads containing every word of `query`, newest first. */
+ searchMessages: channelProcedure
+ .input(
+ z.object({
+ before: z.number().int().positive().optional(),
+ channelId,
+ limit: z.number().int().min(1).max(50).optional(),
+ query: z.string().trim().min(1).max(200),
+ }),
+ )
+ .query(async ({ ctx, input: { channelId, ...options } }) => ({
+ data: await ctx.channelService.repository.searchMessages(channelId, options),
+ success: true,
+ })),
/**
* The caller's direct conversation with an Agent, opened on first use for Agents that predate
* direct Channels. Null when the Agent cannot answer in a Channel (no reachable device).
diff --git a/packages/database/src/repositories/channel/__tests__/search.test.ts b/packages/database/src/repositories/channel/__tests__/search.test.ts
new file mode 100644
index 00000000000..a0e8c972d36
--- /dev/null
+++ b/packages/database/src/repositories/channel/__tests__/search.test.ts
@@ -0,0 +1,97 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { ChannelRepository } from '..';
+import { channelSearchSnippet, channelSearchTerms } from '../search';
+import { createChannelFixture } from './testUtils';
+
+const db = await getTestDB();
+const fixture = createChannelFixture(db, 'channel-search');
+beforeEach(fixture.setup);
+afterEach(fixture.cleanup);
+
+const setup = async () => {
+ const repo = new ChannelRepository(db, fixture.ownerId);
+ const { channel } = await repo.create({ title: 'Planning' });
+ const send = (content: string, requestKey: string, threadId?: string) =>
+ repo.send(channel.id, { content, requestKey, routing: 'fallback', threadId });
+ const root = await send('Should we ship the Search box on Friday?', 'root');
+ const thread = await repo.createThread(channel.id, { rootMessageId: root.id });
+ const reply = await send('Only after QA signs off the search', 'reply', thread.id);
+ const other = await send('Lunch at noon', 'other');
+ const wildcard = await send('Coverage is 100% now', 'wildcard');
+ return { channel, other, reply, repo, root, thread, wildcard };
+};
+
+describe('ChannelRepository.searchMessages', () => {
+ it('finds main and Thread messages case-insensitively, newest first', async () => {
+ const { channel, reply, repo, root, thread } = await setup();
+ const result = await repo.searchMessages(channel.id, { query: 'SEARCH' });
+
+ expect(result.hasMore).toBe(false);
+ expect(result.messages.map((m) => m.id)).toEqual([reply.id, root.id]);
+ expect(result.messages[0]).toMatchObject({
+ author: { id: fixture.ownerId, type: 'user' },
+ threadId: thread.id,
+ });
+ expect(result.messages[1]).toMatchObject({ threadId: null, threadTitle: null });
+ });
+
+ it('requires every word and matches LIKE metacharacters literally', async () => {
+ const { channel, repo, root, wildcard } = await setup();
+ expect(
+ (await repo.searchMessages(channel.id, { query: 'friday search' })).messages.map(
+ (m) => m.id,
+ ),
+ ).toEqual([root.id]);
+ expect(
+ (await repo.searchMessages(channel.id, { query: '100%' })).messages.map((m) => m.id),
+ ).toEqual([wildcard.id]);
+ expect((await repo.searchMessages(channel.id, { query: '_' })).messages).toEqual([]);
+ });
+
+ it('pages older results with `before`', async () => {
+ const { channel, reply, repo, root } = await setup();
+ const first = await repo.searchMessages(channel.id, { limit: 1, query: 'search' });
+ expect(first).toMatchObject({ hasMore: true, messages: [{ id: reply.id }] });
+ const next = await repo.searchMessages(channel.id, {
+ before: first.messages[0].sequence,
+ limit: 1,
+ query: 'search',
+ });
+ expect(next).toMatchObject({ hasMore: false, messages: [{ id: root.id }] });
+ });
+
+ it('skips a trashed Thread', async () => {
+ const { channel, repo, root, thread } = await setup();
+ await repo.removeThread(channel.id, thread.id);
+ expect(
+ (await repo.searchMessages(channel.id, { query: 'search' })).messages.map((m) => m.id),
+ ).toEqual([root.id]);
+ });
+
+ it('hides a Channel the caller cannot read', async () => {
+ const { channel } = await setup();
+ const outsider = new ChannelRepository(db, fixture.memberId);
+ await expect(outsider.searchMessages(channel.id, { query: 'search' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+});
+
+describe('channel search helpers', () => {
+ it('splits and dedupes words', () => {
+ expect(channelSearchTerms(' a b a ')).toEqual(['a', 'b']);
+ expect(channelSearchTerms(' ')).toEqual([]);
+ });
+
+ it('keeps a window around the first match', () => {
+ const content = `${'x'.repeat(200)} needle ${'y'.repeat(300)}`;
+ const snippet = channelSearchSnippet(content, ['NEEDLE']);
+ expect(snippet.startsWith('…')).toBe(true);
+ expect(snippet.endsWith('…')).toBe(true);
+ expect(snippet).toContain('needle');
+ expect(channelSearchSnippet('short\n\ntext', ['zzz'])).toBe('short text');
+ });
+});
diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.ts
index b04eb9e80ff..e2a6f99f98c 100644
--- a/packages/database/src/repositories/channel/index.ts
+++ b/packages/database/src/repositories/channel/index.ts
@@ -54,6 +54,7 @@ import { joinPublicChannel, listJoinableChannels } from './publicAccess';
import { retryJob } from './retry';
import { retryRouting } from './routing';
import type { ChannelSendInput } from './send';
+import { type ChannelSearchOptions, searchChannelMessages } from './search';
import { sendMessage } from './send';
import type { ChannelStopScope } from './stop';
import { stopScope } from './stop';
@@ -483,6 +484,18 @@ export class ChannelRepository {
minRole: 'admin',
});
+ /** Messages in a Channel the caller can read, its live Threads included, matching `query`. */
+ searchMessages = async (channelId: string, options: ChannelSearchOptions) => {
+ const access = await this.findAccess(channelId);
+ return this.db.transaction(async (tx) => {
+ const readable = access
+ ? !access.channel.isDeleted
+ : !!(await findOpenChannel(tx, this.userId, this.workspaceId, channelId));
+ if (!readable) throw new ChannelError('NOT_FOUND', 'Channel not found');
+ return searchChannelMessages(tx, channelId, options);
+ });
+ };
+
detail = async (channelId: string, options?: Parameters<typeof readChannelView>[2]) => {
if (!(await this.findAccess(channelId)))
return readOpenChannel(this.db, this.userId, this.workspaceId, channelId, options);
diff --git a/packages/database/src/repositories/channel/search.ts b/packages/database/src/repositories/channel/search.ts
new file mode 100644
index 00000000000..c396e94e252
--- /dev/null
+++ b/packages/database/src/repositories/channel/search.ts
@@ -0,0 +1,86 @@
+import { and, desc, eq, isNull, lt, or } from 'drizzle-orm';
+
+import { agents, channelMessages, channelThreads, users } from '../../schemas';
+import type { Transaction } from '../../type';
+import { ilikeContains } from '../../utils/like';
+import { notTrashed } from '../../utils/softDelete';
+import { publicMessage, publicMessageColumns } from './view';
+
+export const CHANNEL_SEARCH_MAX_LIMIT = 50;
+/** Characters of context kept on each side of the first match. */
+const SNIPPET_CONTEXT = 80;
+
+export interface ChannelSearchOptions {
+ /** Only messages older than this sequence; pass the last result's to read the next page. */
+ before?: number;
+ limit?: number;
+ query: string;
+}
+
+/** Whitespace-separated words; a message matches when it contains every one of them. */
+export const channelSearchTerms = (query: string) =>
+ [...new Set(query.trim().split(/\s+/).filter(Boolean))].slice(0, 8);
+
+/** A window of the content around the first term found, so a long message stays one row. */
+export const channelSearchSnippet = (content: string, terms: string[]) => {
+ const flat = content.replaceAll(/\s+/g, ' ').trim();
+ const lower = flat.toLowerCase();
+ const hits = terms.map((term) => lower.indexOf(term.toLowerCase())).filter((at) => at >= 0);
+ const at = hits.length ? Math.min(...hits) : 0;
+ const start = Math.max(0, at - SNIPPET_CONTEXT);
+ const end = Math.min(flat.length, at + SNIPPET_CONTEXT * 2);
+ return `${start > 0 ? '…' : ''}${flat.slice(start, end)}${end < flat.length ? '…' : ''}`;
+};
+
+/**
+ * Messages of one Channel, its live Threads included, containing every word of `query`, newest
+ * first. The caller has already authorized reading the Channel.
+ */
+export const searchChannelMessages = async (
+ tx: Transaction,
+ channelId: string,
+ options: ChannelSearchOptions,
+) => {
+ const terms = channelSearchTerms(options.query);
+ if (!terms.length) return { hasMore: false, messages: [] };
+ const limit = Math.max(1, Math.min(options.limit ?? 20, CHANNEL_SEARCH_MAX_LIMIT));
+ const rows = await tx
+ .select({ ...publicMessageColumns, threadMetadata: channelThreads.metadata })
+ .from(channelMessages)
+ .leftJoin(users, eq(users.id, channelMessages.userId))
+ .leftJoin(agents, eq(agents.id, channelMessages.agentId))
+ .leftJoin(
+ channelThreads,
+ and(
+ eq(channelThreads.channelId, channelMessages.channelId),
+ eq(channelThreads.id, channelMessages.threadId),
+ ),
+ )
+ .where(
+ and(
+ eq(channelMessages.channelId, channelId),
+ // A trashed Thread's messages are out of reach, as when opening it.
+ or(isNull(channelMessages.threadId), notTrashed(channelThreads.isDeleted)),
+ options.before === undefined ? undefined : lt(channelMessages.sequence, options.before),
+ ...terms.map((term) => ilikeContains(channelMessages.content, term)),
+ ),
+ )
+ .orderBy(desc(channelMessages.sequence))
+ .limit(limit + 1);
+ return {
+ hasMore: rows.length > limit,
+ messages: rows.slice(0, limit).map(({ threadMetadata, ...row }) => {
+ const { author, content, createdAt, id, sequence, threadId } = publicMessage(row, []);
+ const title = threadMetadata?.title;
+ return {
+ author,
+ createdAt,
+ id,
+ sequence,
+ snippet: channelSearchSnippet(content, terms),
+ threadId,
+ threadTitle: typeof title === 'string' && title ? title : null,
+ };
+ }),
+ };
+};
diff --git a/packages/database/src/repositories/channel/view.ts b/packages/database/src/repositories/channel/view.ts
index 8fbd86bab8f..803d6ab5705 100644
--- a/packages/database/src/repositories/channel/view.ts
+++ b/packages/database/src/repositories/channel/view.ts
@@ -36,7 +36,7 @@ import { activeMembers } from './delivery';
import { ChannelError } from './error';
import { externalWorksByMessage } from './works';
-const publicMessageColumns = {
+export const publicMessageColumns = {
...getTableColumns(channelMessages),
senderAgentAvatar: agents.avatar,
senderAgentName: agents.name,
@@ -55,7 +55,7 @@ type MessageRow = typeof channelMessages.$inferSelect & {
senderUsername: string | null;
};
-const publicMessage = (row: MessageRow, fileIds: string[]) => {
+export const publicMessage = (row: MessageRow, fileIds: string[]) => {
const {
senderAgentAvatar,
senderAgentName,