Repository navigation
Description
Problem
Native thread search (bb thread search, the sidebar Search action, GET /api/v1/threads/search) indexes only text segments: title, title_fallback, user_message, assistant_message, system_message. It does not index the provider session identity (providerThreadId) that BB already stores on every event. As a result a thread cannot be found by the provider session UUID that the operator sees in provider logs, --resume commands, session files, or external session indexes, unless that UUID happens to be quoted inside message text.
Two facts make this worse than "one missing field":
- One BB thread accumulates more than one
providerThreadId. Editing an earlier message (rewind) or a provider restart yields a replacement provider session; later events carry the new id. BB keeps only the last alias in memory and ingetLastProviderThreadId. There is no persisted alias set, so nothing can answer "which thread owned session X" for the initial alias once it has been replaced. - Plugins cannot contribute results to native search. A plugin that maintains its own local index (for example a traces plugin over provider session logs) can call
sdk.threads.search, and the sidebar-navigation surface lets a plugin replace the Search action, but there is no provider surface through which native search can pull federated results into the active/archived groups.
Reproduction (sanitized)
- Start a thread on a provider that reports session identity (Claude Code, Codex). Read its provider session id:
bb thread log <thr_id> --jsonand takeproviderThreadIdfrom anyitem/completedevent. bb thread search <that uuid> --jsonwhile the thread is live and before any message quotes the id ->active.total: 0,archived.total: 0. The same for an 8-character prefix.- Edit an earlier message (rewind). Later events carry a second
providerThreadId. Search for the first alias -> still 0. - Archive the thread. Search for either alias -> 0 in both groups.
- Control:
bb thread search "<a word from the title>"finds the thread, so the index itself is healthy.
Observed on bb desktop 0.40.0 (bb --version), host DB ~/.bb/bb.db, read-only aggregates only (no thread ids or UUIDs recorded here):
| aggregate | value |
|---|---|
| threads | 222 |
threads with at least one events.provider_thread_id |
218 |
| distinct (thread, provider_thread_id) pairs | 221 |
| threads carrying 2 aliases (edit/restart) | 3, one of them archived |
| pairs whose alias text appears in no search segment of the owning thread (unreachable by search) | 102 of 221 (46%), 68 of them on archived threads |
| pairs reachable at all | 119, and only because a local hook on this host echoes the session id into reply text |
Even the "reachable" ones are reached by accident: for one two-alias thread, searching its alias returned other threads that had quoted the UUID and did not return the owning thread. On a host without that hook the unreachable share is expected to be ~100%.
Current main evidence
Verified against main at 1dfed079b2b4bc06bdc45c96688e8e9b8a14a956:
- Search source kinds are a closed enum of five text kinds, no identity kind:
bb/packages/domain/src/thread-search.ts
Lines 3 to 9 in 1dfed07
const threadSearchSourceKindValues = [ "title", "title_fallback", "user_message", "assistant_message", "system_message", ] as const; - The index is
thread_search_segments+ an FTS5 table overtextonly (migrations0039,0040,0101): https://github.com/get-bb/bb/blob/1dfed079b2b4bc06bdc45c96688e8e9b8a14a956/packages/db/drizzle/0039_thread_search.sql andLines 600 to 624 in 1dfed07
export const threadSearchSegments = sqliteTable( "thread_search_segments", { id: text("id").primaryKey(), threadId: text("thread_id") .notNull() .references(() => threads.id, { onDelete: "cascade" }), sourceKind: text("source_kind").$type<ThreadSearchSourceKind>().notNull(), sourceKey: text("source_key").notNull(), sourceSeq: integer("source_seq"), text: text("text").notNull(), createdAt: integer("created_at").notNull(), updatedAt: integer("updated_at").notNull(), }, (table) => [ uniqueIndex("thread_search_segments_source_idx").on( table.threadId, table.sourceKind, table.sourceKey, ), index("thread_search_segments_thread_source_seq_idx").on( table.threadId, table.sourceSeq, ), ], - The match query joins only
thread_search_segments_fts->thread_search_segments->threads; nothing readsevents.provider_thread_id:andbb/packages/db/src/data/threads.ts
Lines 959 to 1010 in 1dfed07
function listThreadSearchMatchRows( db: DbConnection, args: ListThreadSearchMatchRowsArgs, ): ThreadSearchMatchRow[] { const tokenMatchSelects = args.tokenMatchQueries.map( (matchQuery, tokenIndex) => sql` SELECT s.thread_id AS threadId, ${tokenIndex} AS tokenIndex, MIN(thread_search_segments_fts.rank) AS tokenRank FROM thread_search_segments_fts JOIN thread_search_segments AS s ON s.rowid = thread_search_segments_fts.rowid WHERE thread_search_segments_fts MATCH ${matchQuery} GROUP BY s.thread_id `, ); const isTitleSegment = sql`thread_search_segments.source_kind IN ('title', 'title_fallback')`; return db.all<ThreadSearchMatchRow>(sql` WITH token_matches AS ( ${sql.join(tokenMatchSelects, sql` UNION ALL `)} ), ranked_threads AS ( SELECT token_matches.threadId AS threadId, MIN(token_matches.tokenRank) AS bestRank, MAX(t.updated_at) AS threadUpdatedAt, MAX(t.archived_at IS NOT NULL) AS archived FROM token_matches JOIN threads AS t ON t.id = token_matches.threadId WHERE t.deleted_at IS NULL AND t.visibility = 'visible' GROUP BY threadId HAVING COUNT(DISTINCT token_matches.tokenIndex) = ${args.tokenMatchQueries.length} ), ordered_threads AS ( SELECT threadId, archived, ROW_NUMBER() OVER ( PARTITION BY archived ORDER BY bestRank ASC, threadUpdatedAt DESC, threadId DESC ) AS threadOrder, COUNT(*) OVER (PARTITION BY archived) AS total FROM ranked_threads ), limited_threads AS ( SELECT threadId, archived, threadOrder, total FROM ordered_threads WHERE threadOrder <= ${args.limitPerGroup} ), bb/packages/db/src/data/threads.ts
Lines 1109 to 1143 in 1dfed07
export function searchThreadsWithPendingInteractionState( db: DbConnection, args: SearchThreadsWithPendingInteractionStateArgs, ): ThreadSearchResults { const tokens = listThreadSearchQueryTokens(args.query); const tokenMatchQueries = listThreadSearchTokenMatchQueries(tokens); const anyTokenMatchQuery = buildThreadSearchAnyTokenMatchQuery(tokenMatchQueries); if (anyTokenMatchQuery === null) { return { active: { total: 0, results: [] }, archived: { total: 0, results: [] }, }; } const limitPerGroup = Math.min( Math.max(args.limitPerGroup, 1), THREAD_SEARCH_LIMIT_PER_GROUP_MAX, ); const rows = listThreadSearchMatchRows(db, { anyTokenMatchQuery, limitPerGroup, tokenMatchQueries, }); return { active: hydrateThreadSearchGroup(db, { tokens, rows: rows.filter((row) => row.archived === 0), }), archived: hydrateThreadSearchGroup(db, { tokens, rows: rows.filter((row) => row.archived === 1), }), }; } providerThreadIdis persisted per event (events.provider_thread_id), so the data to index already exists:Lines 661 to 673 in 1dfed07
export const events = sqliteTable( "events", { id: text("id").primaryKey(), threadId: text("thread_id") .notNull() .references(() => threads.id, { onDelete: "cascade" }), environmentId: text("environment_id").references(() => environments.id, { onDelete: "set null", }), scopeKind: text("scope_kind").$type<ThreadEventScopeKind>().notNull(), turnId: text("turn_id"), providerThreadId: text("provider_thread_id"), - Runtime identity is a single in-memory
threadId -> providerThreadIdmap, overwritten on each identity notification, and the server reads only the last stored alias:,bb/packages/agent-runtime/src/runtime-thread-identity.ts
Lines 50 to 51 in 1dfed07
private readonly threadToProvider = new Map<string, string>(); private readonly threadToProviderThread = new Map<string, string>(); ,bb/packages/agent-runtime/src/runtime-thread-identity.ts
Lines 96 to 98 in 1dfed07
resolveBbThreadIdForProviderThread( args: ResolveBbThreadIdForProviderThreadArgs, ): string | undefined { bb/apps/server/src/services/threads/thread-events.ts
Lines 972 to 977 in 1dfed07
export function getLastProviderThreadId( deps: ThreadEventReadDeps, threadId: string, ): string | null { return getLastStoredProviderThreadId(deps.db, threadId); } - Message edit stages a new
providerThreadIdfromthread.rewind.prepare, which is how a thread gets a replacement alias:bb/apps/server/src/services/threads/thread-edit-message.ts
Lines 495 to 507 in 1dfed07
}); const prepared: HostDaemonCommandResult<"thread.rewind.prepare"> = await runLiveHostCommand(deps, { command: rewindPrepareCommandFromStart(startCommand, { leaseId: rewindLeaseId, retainThroughProviderCheckpoint: target.precedingProviderCheckpoint, sourceProviderThreadId: target.sourceProviderThreadId, }), hostId: readyEnvironment.hostId, timeoutMs: LIVE_DAEMON_COMMAND_TIMEOUT_MS, }); stagedProviderThreadId = prepared.providerThreadId; } - Search route, contract and CLI accept only
query+limitPerGroup:,bb/apps/server/src/routes/threads/base.ts
Lines 301 to 319 in 1dfed07
get(routes.search, (context, query) => { const searchQuery = query.query.trim(); if (countNonWhitespaceChars(searchQuery) < 2) { throw new ApiError( 400, "invalid_request", "query must contain at least two non-whitespace characters", ); } const limitPerGroup = parseSearchLimitPerGroup(query.limitPerGroup); return context.json( buildThreadSearchResponse(deps, { ...searchThreadsWithPendingInteractionState(deps.db, { query: searchQuery, limitPerGroup, }), }) satisfies ThreadSearchResponse, ); }); ,bb/packages/server-contract/src/api/threads.ts
Lines 792 to 795 in 1dfed07
export const threadSearchQuerySchema = z.object({ query: z.string().trim().min(2), limitPerGroup: z.string().regex(/^\d+$/).optional(), }); bb/apps/cli/src/commands/thread/organization.ts
Lines 242 to 256 in 1dfed07
.command("search <query>") .description("Search threads and messages") .option( "--limit <count>", `Maximum results per group (1-${THREAD_SEARCH_LIMIT_PER_GROUP_MAX})`, ) .option("--json", "Print machine-readable JSON output") .action( action(async (query: string, opts: SearchOptions) => { const result = await createCliBbSdk(getUrl()).threads.search({ query, limitPerGroup: parsePositiveInteger( opts.limit, "--limit", THREAD_SEARCH_LIMIT_PER_GROUP_MAX, - App search hook and sidebar entry point: ,
export function useThreadSearch({ searchThreads: () => { - Plugin surfaces:
sidebar-navigationcan arrange or replace the Search action,thread-listexplicitly keeps "the search action" as bb's, and the only plugin-sidesearch()contract is the mention provider. Plugins receivesdk.threads(so they can call native search) but native search has no hook to call them:,bb/packages/plugin-api-map/src/surfaces.ts
Lines 61 to 90 in 1dfed07
id: "sidebar-navigation", title: "Sidebar navigation", summary: "Replaces bb's navigation controls above the thread list with a component your plugin renders. With this, a plugin can:", bullets: [ "Arrange New thread, Search, Extensions, and plugin destinations", "Activate each destination through bb, including split placement for supported items", "Render bb's original controls when the plugin wants to delegate", "Leave the thread list, footer, drawer, and resize handle under bb's control", ], apiSymbols: [ "ExperimentalSidebarNavigationRegistration", "ExperimentalSidebarNavigationProps", "ExperimentalSidebarNavigationItem", "ExperimentalSidebarNavigationAction", "ExperimentalSidebarNavigationIcon", "ExperimentalSidebarNavigationShortcut", "ExperimentalSidebarNavigationActivationOptions", ], experimental: true, }, { id: "thread-list", title: "The thread list", summary: "Replaces the list of threads in bb's sidebar with a component your plugin renders. With this, a plugin can:", bullets: [ "Render every row, and decide the grouping, the ordering, and what each row shows", "Read the same live thread data and run statuses bb's own list reads", "Replace only the list. The New thread button, the search action, the plugin rows, and the sidebar footer stay bb's", ,bb/packages/plugin-sdk/src/backend-contract.ts
Lines 1315 to 1351 in 1dfed07
/** Search context handed to a mention provider (design §4.9). `projectId`/ * `threadId` are null when the composer has not committed one yet. */ export interface PluginMentionSearchContext { trigger: PluginMentionTrigger; query: string; projectId: string | null; threadId: string | null; } /** One row a mention provider returns from `search`. `id` is the provider's * own item id — the host namespaces it before it reaches the wire. */ export interface PluginMentionItem { id: string; title: string; subtitle?: string; icon?: string; } export interface PluginMentionProviderRegistration { /** Unique within this plugin: [a-zA-Z0-9_-]+ (no ":" — the host composes * wire item ids as "<providerId>:<itemId>"). */ id: string; /** Section label shown above this provider's rows in the mention menu. */ label: string; /** * Composer trigger characters this provider should answer. Omit to use the * default `@` mention trigger. Valid triggers are `@`, `#`, `$`, `!`, and `~`. */ triggers?: readonly PluginMentionTrigger[]; /** * Runs server-side as the user types after one of this provider's triggers * in the composer. Each call is time-boxed (2s) and failure-isolated: a slow * or throwing provider contributes an empty list — it can never break the * mention menu. */ search( ctx: PluginMentionSearchContext, bb/apps/server/src/services/plugins/plugin-api.ts
Lines 272 to 273 in 1dfed07
threads: { ...sdk.threads,
Proposed architecture
A. Persist the alias set (BB-owned correlation record).
New table thread_provider_identities (thread_id, provider_id, provider_thread_id, first_seen_seq, last_seen_seq, created_at, updated_at) with UNIQUE (provider_id, provider_thread_id) and an index on provider_thread_id. Upsert it wherever an event with providerThreadId is appended (same write path that already fills events.provider_thread_id). One-shot backfill migration: INSERT ... SELECT DISTINCT thread_id, provider_thread_id, MIN(sequence), MAX(sequence) FROM events WHERE provider_thread_id IS NOT NULL GROUP BY 1,2. This is also option 2 of #2134, so both issues can share the table.
B. Resolve identity queries before FTS, not through it.
In searchThreadsWithPendingInteractionState, when the trimmed query looks like a UUID or a hex prefix of >= 6 chars, run an indexed lookup provider_thread_id = ? / LIKE 'prefix%' on the alias table, and merge the owning threads into the result set as a match with a new sourceKind: "provider_thread_id" (text = the alias, highlight = the matched span), ranked above text matches. Keep FTS untouched: unicode61 splits a UUID into five tokens and the prefix = '2 3' index does not help an 8-char prefix, so putting aliases into the FTS table would be both slower and less exact. Alternatively add the alias as a thread_search_segments row with the new source kind so the existing hydration and snippet code applies; the exact-lookup path is still needed for prefixes.
C. Optional plugin search-provider surface.
api.search.registerThreadSearchProvider({ id, search(ctx: { query, projectId?, limitPerGroup, signal }) => Promise<Array<{ threadId, matches: Array<{ sourceKind: "plugin", pluginId, text, highlightRanges }> }>> }). Native search runs providers in parallel with the SQLite query under a fixed budget (e.g. 150 ms, AbortSignal), merges by threadId, assigns active/archived from BB's own threads row, drops unknown or deleted thread ids, and drops a provider that throws or times out without failing the request. threadSearchMatchSchema.sourceKind gains "plugin" (+ optional pluginId) as an additive contract change. This lets a local index such as a traces plugin over provider session logs answer "which thread ran session X" even when the id never entered a message, and composes with project scoping from #2710.
Performance constraints
- The search route is a synchronous SQLite call on the request path. Alias resolution must be an indexed point/prefix lookup, never a scan of
events(192k rows on this host). - One alias row per (thread, alias), not per event; the FTS table is not widened.
- Backfill is a single indexed
INSERT ... SELECT, safe to run on databases with hundreds of thousands of events. - Plugin providers: bounded budget, parallel to native, failure-isolated. Native results are never delayed past the budget.
Acceptance tests
- Active thread, initial alias: fixture thread whose messages do not contain the UUID;
search(<full uuid>)returns the owning thread inactivewith aprovider_thread_idmatch. Same for the first 8 characters. - Replacement alias: after an edit/rewind the thread has two aliases; searching either returns the same thread exactly once (deduplicated), with the matched alias in the match text.
- Archived thread: both aliases return the thread in
archived, notactive. - Stable
thr_navigation: every result carries the BB thread id; opening a result navigates to thatthr_id regardless of which alias matched;bb thread show <thr_id>and--resume-style flows are unchanged. - Exclusions unchanged: deleted (
deleted_at) and non-visible threads are never returned via an alias. - Ranking and limits: alias matches rank above text matches;
limitPerGroupandactive/archivedtotals count alias-only threads correctly and compose with--projectfrom Allow bb thread search to scope results to a project #2710. - Backfill: a database that already has
events.provider_thread_idvalues is searchable by every historical alias after migration, including aliases only present on archived threads. - Plugin provider (if C is accepted): a test plugin returning a thread id for a query that matches no native segment yields a
pluginmatch in the correct group; a provider that throws or exceeds the budget is ignored and native results are still returned; results for unknown thread ids are dropped. - Contract and CLI:
bb thread search --json, the SDKthreads.search, and the app search hook accept the newsourceKindvalues without breaking existing consumers.
Duplicate check
Open-and-closed issue search on search, thread search, providerThreadId, session id, resume, plugin search, find thread, sidebar search, archived found no issue covering alias indexing or federated plugin results. Related but distinct: #2710 (project scope for bb thread search), #2134 (turn-completion hook / correlation record; part A here would satisfy its option 2), #1710 (archived threads resume), #1028 (import an existing provider session as a thread).
Activity
bb-slop-cop commentedon Sep 1, 2026
🚨 SLOP COP 🚨 ·
new-issue-autopilotthreads,plugins,confirmed-repro.confirmed-repro.