🤯 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(task): search task description and instruction in global search (#22256)
Rdmclin20069d8bae735
diff --git a/packages/database/src/repositories/taskSearch/index.test.ts b/packages/database/src/repositories/taskSearch/index.test.tsindex a52efc9fbcd..f2c45ab3c34 100644--- a/packages/database/src/repositories/taskSearch/index.test.ts+++ b/packages/database/src/repositories/taskSearch/index.test.ts@@ -85,6 +85,118 @@ describe('TaskSearchRepo', () => {expect(untitled.title).toBe('T-3');});+ it('finds a task by a phrase in its instruction and shows the matched passage', async () => {+ const model = new TaskModel(serverDB, userId);+ const task = await model.create({+ instruction: [+ '',+ '',+ 'The **resource drive** toolbar has a batch-actions button that does nothing when clicked, so files cannot be moved.',+ ].join('\n'),+ name: 'Drive bug',+ });++ const results = await new TaskSearchRepo(serverDB, userId).search({ query: 'Does Nothing' });++ expect(results).toHaveLength(1);+ expect(results[0]).toMatchObject({ id: task.id, relevance: 5, title: 'Drive bug' });+ expect(results[0].description).toBe(+ '…toolbar has a batch-actions button that does nothing when clicked, so files cannot be moved.',+ );+ });++ it('finds a task by its description and keeps the description as subtitle', async () => {+ const model = new TaskModel(serverDB, userId);+ const task = await model.create({+ description: 'Customer escalation from Acme',+ instruction: 'Investigate the report',+ name: 'Escalation',+ });++ const [result] = await new TaskSearchRepo(serverDB, userId).search({ query: 'acme' });++ expect(result).toMatchObject({+ description: 'Customer escalation from Acme',+ id: task.id,+ relevance: 5,+ });+ });++ it('shows the matched passage instead of a description without the term', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({ description: 'Short summary', instruction: 'Refactor widget', name: 'X' });++ const [result] = await new TaskSearchRepo(serverDB, userId).search({ query: 'widget' });++ expect(result.description).toBe('Refactor widget');+ });++ it('ranks name matches ahead of content-only matches', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({ instruction: 'Mention payments in the body', name: 'Body only' });+ await model.create({ instruction: 'Unrelated', name: 'Fix payments retry' });++ const results = await new TaskSearchRepo(serverDB, userId).search({ query: 'payments' });++ expect(results.map((r) => [r.title, r.relevance])).toEqual([+ ['Fix payments retry', 4],+ ['Body only', 5],+ ]);+ });++ it('falls back to the opening text when the match is inside stripped markdown', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({+ instruction: '\n\nSee the screenshot',+ name: 'Shot',+ });++ const [result] = await new TaskSearchRepo(serverDB, userId).search({ query: 'file_zzz' });++ expect(result.description).toBe('See the screenshot');+ });++ it.each(['retry_count', 'C#'])(+ 'keeps literal punctuation such as %s in the matched passage',+ async (query) => {+ const model = new TaskModel(serverDB, userId);+ await model.create({+ instruction: `${'Background context that pushes the match past the opening. '.repeat(3)}Then rename ${query} in the worker.`,+ name: 'Punctuation',+ });++ const [result] = await new TaskSearchRepo(serverDB, userId).search({ query });++ expect(result.description).toContain(`rename ${query} in the worker.`);+ expect(result.description?.startsWith('…')).toBe(true);+ },+ );++ it('finds a passage across stripped markdown and drops heading markers', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({+ instruction: '## Steps\n\nClick the **batch** button',+ name: 'Markdown',+ });++ const repo = new TaskSearchRepo(serverDB, userId);+ const [byHeading] = await repo.search({ query: 'Steps' });+ expect(byHeading.description).toBe('Steps Click the batch button');++ const [byRawMarkdown] = await repo.search({ query: '**batch** button' });+ expect(byRawMarkdown.description).toBe('Steps Click the batch button');+ });++ it('treats LIKE wildcards in the content literally', async () => {+ const model = new TaskModel(serverDB, userId);+ await model.create({ instruction: 'Coverage must reach 100%', name: 'A' });+ await model.create({ instruction: 'Coverage must reach 1000 lines', name: 'B' });++ const results = await new TaskSearchRepo(serverDB, userId).search({ query: '100%' });++ expect(results.map((r) => r.title)).toEqual(['A']);+ });+it('treats LIKE wildcards in the query literally', async () => {const model = new TaskModel(serverDB, userId);await createTasks(model, ['Raise to 100%', 'Raise to 1000']);diff --git a/packages/database/src/repositories/taskSearch/index.ts b/packages/database/src/repositories/taskSearch/index.tsindex e37857aae90..eb619f9188d 100644--- a/packages/database/src/repositories/taskSearch/index.ts+++ b/packages/database/src/repositories/taskSearch/index.ts@@ -14,8 +14,49 @@ export interface TaskSearchOptions {/** A bare task number (`827` or `#827`) — longer runs cannot be a valid `seq`. */const SEQ_PATTERN = /^#?(\d{1,9})$/;+/** Characters of context kept on each side of a content match in the snippet. */+const SNIPPET_CONTEXT = 40;++/**+ * Markdown syntax that would crowd a one-line snippet: images, link targets,+ * line-leading heading/quote markers, bold markers and backticks. Literal+ * characters a query may contain (`retry_count`, `C#`) are kept.+ */+const toPlainText = (markdown: string) =>+ markdown+ .replaceAll(/!\[[^\]]*]\([^)]*\)/g, ' ')+ .replaceAll(/\[([^\]]*)]\([^)]*\)/g, '$1')+ .replaceAll(/^\s*(?:#{1,6}|>+)\s+/gm, '')+ .replaceAll(/\*\*|`+/g, '')+ .replaceAll(/\s+/g, ' ')+ .trim();+/**- * Command-menu lookup for tasks by identifier or name.+ * The instruction text around the first match, so a result found only by its+ * body still shows why it matched. Falls back to the body's opening when the+ * match sits inside markdown that `toPlainText` stripped (an image URL).+ */+const buildSnippet = (instruction: string, needle: string): string | null => {+ const text = toPlainText(instruction);+ if (!text) return null;++ const haystack = text.toLowerCase();+ // A query that spans stripped syntax (`**bold** text`) is found once it is+ // normalized the same way as the body.+ const term = [needle, toPlainText(needle)]+ .map((candidate) => candidate.toLowerCase())+ .find((candidate) => candidate && haystack.includes(candidate));+ const index = term ? haystack.indexOf(term) : -1;+ const start = index < 0 ? 0 : Math.max(0, index - SNIPPET_CONTEXT);+ const end =+ index < 0 ? SNIPPET_CONTEXT * 2 : Math.min(text.length, index + term!.length + SNIPPET_CONTEXT);++ return `${start > 0 ? '…' : ''}${text.slice(start, end).trim()}${end < text.length ? '…' : ''}`;+};++/**+ * Command-menu lookup for tasks by identifier, name, or content (description+ * and instruction).** Tasks are not part of the full-text index, so this queries the `tasks` table* directly with the same visibility-aware ownership as `TaskModel.ownership()`:@@ -39,13 +80,15 @@ export class TaskSearchRepo {: identifierExact;const identifierPrefix = sql`${tasks.identifier} ILIKE ${`${escapeLike(text)}%`} ESCAPE '\\'`;const namePrefix = sql`${tasks.name} ILIKE ${`${escapeLike(text)}%`} ESCAPE '\\'`;+ const nameContains = ilikeContains(tasks.name, text);// Lower is better, matching FtsSearchBaseResult.relevance.const relevance = sql<number>`CASEWHEN ${exact} THEN 1WHEN ${identifierPrefix} THEN 2WHEN ${namePrefix} THEN 3- ELSE 4+ WHEN ${nameContains} THEN 4+ ELSE 5END`;const rows = await this.db@@ -55,6 +98,7 @@ export class TaskSearchRepo {description: tasks.description,id: tasks.id,identifier: tasks.identifier,+ instruction: tasks.instruction,name: tasks.name,relevance,status: tasks.status,@@ -72,14 +116,28 @@ export class TaskSearchRepo {workspaceId: tasks.workspaceId,},),- or(exact, identifierPrefix, ilikeContains(tasks.name, text)),+ or(+ exact,+ identifierPrefix,+ nameContains,+ ilikeContains(tasks.description, text),+ ilikeContains(tasks.instruction, text),+ ),),).orderBy(asc(relevance), desc(tasks.updatedAt), desc(tasks.seq)).limit(limit);- return rows.map(({ name, relevance, ...row }) => ({+ const needle = text.toLowerCase();++ return rows.map(({ description, instruction, name, relevance, ...row }) => ({...row,+ // A body-only match shows the matched passage unless the description+ // already carries the term.+ description:+ Number(relevance) === 5 && instruction && !description?.toLowerCase().includes(needle)+ ? buildSnippet(instruction, text)+ : description,relevance: Number(relevance),title: name || row.identifier,type: 'task' as const,