π€― 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
π fix(search): hydrate candidates by primary key, hide verifier prompts, flatten table cells (#22013)
Arvin Xu5c8edbf3a2aa
diff --git a/apps/cli/src/utils/format.test.ts b/apps/cli/src/utils/format.test.tsindex 29e8b4b2d6e..3bc827caa75 100644--- a/apps/cli/src/utils/format.test.ts+++ b/apps/cli/src/utils/format.test.ts@@ -1,6 +1,13 @@import { describe, expect, it, vi } from 'vitest';-import { formatCost, formatNumber, outputJson, printBoxTable, timeUntil } from './format';+import {+ formatCost,+ formatNumber,+ outputJson,+ printBoxTable,+ printTable,+ timeUntil,+} from './format';describe('formatNumber', () => {it('should format numbers with commas', () => {@@ -165,6 +172,29 @@ describe('printBoxTable', () => {});});+describe('printTable', () => {+ it('keeps a multi-line cell on its own row', () => {+ const lines: string[] = [];+ const spy = vi.spyOn(console, 'log').mockImplementation((line: string) => lines.push(line));++ printTable(+ [+ ['tpc_a', 'Check to verify\ncheckItemId: 2d8\r\n done', '2'],+ ['tpc_b', 'Weekly', '1'],+ ],+ ['ID', 'TITLE', 'HITS'],+ );+ spy.mockRestore();++ expect(lines).toHaveLength(3);+ expect(lines.every((line) => !/[\r\n]/.test(line))).toBe(true);+ expect(lines[1]).toContain('Check to verify checkItemId: 2d8 done');+ // Column widths come from the flattened cell, so the last column stays aligned.+ expect(lines[1].trimEnd().endsWith(' 2')).toBe(true);+ expect(lines[2].trimEnd().length).toBe(lines[1].trimEnd().length);+ });+});+describe('timeUntil', () => {// `timeAgo` only formats the past; an invitation expiry is in the future and// rendered "-604800s ago" through it.diff --git a/apps/cli/src/utils/format.ts b/apps/cli/src/utils/format.tsindex b49587ad476..8aa9fd73966 100644--- a/apps/cli/src/utils/format.ts+++ b/apps/cli/src/utils/format.ts@@ -73,7 +73,11 @@ export function truncate(str: string, maxWidth: number): string {return str;}-export function printTable(rows: string[][], header: string[]) {+/** A line break inside a cell (multi-line topic titles) would split its table row. */+const singleLine = (cell: string) => cell.replaceAll(/\s*[\r\n]\s*/g, ' ');++export function printTable(rawRows: string[][], header: string[]) {+ const rows = rawRows.map((row) => row.map((cell) => singleLine(cell || '')));const allRows = [header, ...rows];const colWidths = header.map((_, i) => Math.max(...allRows.map((r) => displayWidth(r[i] || ''))));diff --git a/packages/database/src/models/__tests__/messages/message.keywordSearch.test.ts b/packages/database/src/models/__tests__/messages/message.keywordSearch.test.tsindex f44a7570eda..788fcccc3e3 100644--- a/packages/database/src/models/__tests__/messages/message.keywordSearch.test.ts+++ b/packages/database/src/models/__tests__/messages/message.keywordSearch.test.ts@@ -36,6 +36,10 @@ beforeEach(async () => {{ id: 'kw-task', title: 'T-472 daily report', trigger: 'task', userId },{ id: 'kw-eval', title: 'BrowseComp', trigger: 'eval', userId },{ id: 'kw-doc', title: 'Doc chat', trigger: 'document', userId },+ // Verifier topics: no trigger, but always started under a task.+ { id: 'kw-verify', metadata: { taskId: 'task_kw' }, title: 'Check to verify', userId },+ // A plain chat that happens to have no trigger stays searchable.+ { id: 'kw-legacy', title: 'Legacy chat', userId },]);});@@ -149,6 +153,44 @@ describe('MessageModel.searchByKeyword', () => {expect(byAgent.items.map(({ id }) => id)).toEqual(['kw-in']);});+ it('hides acceptance verifier prompts, which run in trigger-less task topics', async () => {+ const messageModel = await seed([+ {+ content: '## Check to verify checkItemId: x β goal STAMP',+ id: 'kw-verify-prompt',+ role: 'user',+ topicId: 'kw-verify',+ userId,+ },+ {+ content: 'STAMP check passed',+ id: 'kw-verify-reply',+ role: 'assistant',+ topicId: 'kw-verify',+ userId,+ },+ {+ content: 'what is STAMP',+ id: 'kw-legacy-prompt',+ role: 'user',+ topicId: 'kw-legacy',+ userId,+ },+ ]);++ const visible = await messageModel.searchByKeyword({ keyword: 'STAMP' });+ expect(visible.items.map(({ id }) => id).sort()).toEqual([+ 'kw-legacy-prompt',+ 'kw-verify-reply',+ ]);++ const all = await messageModel.searchByKeyword({+ includeAutomatedPrompts: true,+ keyword: 'STAMP',+ });+ expect(all.items.map(({ id }) => id)).toContain('kw-verify-prompt');+ });+it('hides system-written prompts of automation topics unless asked', async () => {const messageModel = await seed([{diff --git a/packages/database/src/models/message/search.ts b/packages/database/src/models/message/search.tsindex 2072bea84e3..9b1e0ca73e0 100644--- a/packages/database/src/models/message/search.ts+++ b/packages/database/src/models/message/search.ts@@ -25,7 +25,6 @@ export const AUTOMATED_PROMPT_TOPIC_TRIGGERS = ['task','task_manager',];-export const MESSAGE_KEYWORD_SEARCH_MAX_LIMIT = 100;/**@@ -217,7 +216,18 @@ export class MessageKeywordSearchQueries extends MessageScope {? undefined: or(ne(messages.role, 'user'),- isNull(topics.trigger),+ // Acceptance verifier prompts ("Check to verify β¦") run without a+ // trigger (it also feeds the run's origin, so it stays unset) but+ // always under their task: a trigger-less topic with+ // `metadata.taskId` is a verifier topic. In production every such+ // topic is one (16,216 of 16,216 over 60 days); human chats about+ // a task carry `trigger: 'chat'`.+ and(+ isNull(topics.trigger),+ // `->> ... IS NULL` on an extracted jsonb value crashes the planner+ // under pg_search, so ask the same question with a COALESCE sentinel.+ sql`COALESCE(${topics.metadata} ->> 'taskId', '') = ''`,+ ),notInArray(topics.trigger, AUTOMATED_PROMPT_TOPIC_TRIGGERS),),];diff --git a/packages/database/src/utils/inJsonStringArray.test.ts b/packages/database/src/utils/inJsonStringArray.test.tsnew file mode 100644index 00000000000..7f7b3fa8097--- /dev/null+++ b/packages/database/src/utils/inJsonStringArray.test.ts@@ -0,0 +1,29 @@+import { PgDialect } from 'drizzle-orm/pg-core';+import { describe, expect, it } from 'vitest';++import { messages } from '../schemas';+import { inJsonStringArray } from './inJsonStringArray';++const render = (values: string[]) =>+ new PgDialect().sqlToQuery(inJsonStringArray(messages.id, values));++describe('inJsonStringArray', () => {+ it('binds the whole set as one JSONB parameter', () => {+ const query = render(['msg_a', 'msg_b']);++ expect(query.params).toEqual(['["msg_a","msg_b"]']);+ });++ it('folds the set into an array so candidates drive an index lookup', () => {+ // `IN (SELECT β¦ jsonb_array_elements_text β¦)` let the planner, which costs+ // any set-returning function at 100 rows, scan the user's whole history.+ const { sql } = render(['msg_a']);++ expect(sql).toMatch(/"id" = ANY\(ARRAY\(\s*SELECT value/);+ expect(sql).not.toMatch(/"id" IN \(/);+ });++ it('matches nothing for an empty set', () => {+ expect(render([]).sql).toBe('false');+ });+});diff --git a/packages/database/src/utils/inJsonStringArray.ts b/packages/database/src/utils/inJsonStringArray.tsindex ba3f1c35919..8d73df68804 100644--- a/packages/database/src/utils/inJsonStringArray.ts+++ b/packages/database/src/utils/inJsonStringArray.ts@@ -5,12 +5,18 @@ import { sql } from 'drizzle-orm';* Match a text column against an arbitrary-size ID set using one JSONB bind parameter.* Candidate-only search can be unbounded, so expanding every ID through `inArray`* would exceed PostgreSQL's bind-parameter limit for large histories.+ *+ * The set is folded into an array (`= ANY(ARRAY(...))`) rather than joined as+ * `IN (SELECT ...)`: the planner estimates any set-returning function at 100+ * rows, so as a semi-join it preferred scanning the caller's whole history by+ * `user_id` and filtering by ID last β minutes for a user with ~1.7M messages.+ * As an array the candidates drive a primary-key index scan instead.*/export const inJsonStringArray = (column: SQLWrapper, values: string[]): SQL<boolean> => {if (values.length === 0) return sql<boolean>`false`;- return sql<boolean>`${column} IN (+ return sql<boolean>`${column} = ANY(ARRAY(SELECT valueFROM jsonb_array_elements_text(${JSON.stringify(values)}::jsonb) AS candidate_ids(value)- )`;+ ))`;};