Skip to content

Thread search does not index providerThreadId aliases, so a thread cannot be found by its provider session id; plugins cannot federate results into native search #2840

Open

Description

@kravtsovd

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":

  1. 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 in getLastProviderThreadId. There is no persisted alias set, so nothing can answer "which thread owned session X" for the initial alias once it has been replaced.
  2. 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)

  1. Start a thread on a provider that reports session identity (Claude Code, Codex). Read its provider session id: bb thread log <thr_id> --json and take providerThreadId from any item/completed event.
  2. bb thread search <that uuid> --json while the thread is live and before any message quotes the id -> active.total: 0, archived.total: 0. The same for an 8-character prefix.
  3. Edit an earlier message (rewind). Later events carry a second providerThreadId. Search for the first alias -> still 0.
  4. Archive the thread. Search for either alias -> 0 in both groups.
  5. 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:
    const threadSearchSourceKindValues = [
    "title",
    "title_fallback",
    "user_message",
    "assistant_message",
    "system_message",
    ] as const;
  • The index is thread_search_segments + an FTS5 table over text only (migrations 0039, 0040, 0101): https://github.com/get-bb/bb/blob/1dfed079b2b4bc06bdc45c96688e8e9b8a14a956/packages/db/drizzle/0039_thread_search.sql and
    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 reads events.provider_thread_id:
    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}
    ),
    and
    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),
    }),
    };
    }
  • providerThreadId is persisted per event (events.provider_thread_id), so the data to index already exists:
    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 -> providerThreadId map, overwritten on each identity notification, and the server reads only the last stored alias:
    private readonly threadToProvider = new Map<string, string>();
    private readonly threadToProviderThread = new Map<string, string>();
    ,
    resolveBbThreadIdForProviderThread(
    args: ResolveBbThreadIdForProviderThreadArgs,
    ): string | undefined {
    ,
    export function getLastProviderThreadId(
    deps: ThreadEventReadDeps,
    threadId: string,
    ): string | null {
    return getLastStoredProviderThreadId(deps.db, threadId);
    }
  • Message edit stages a new providerThreadId from thread.rewind.prepare, which is how a thread gets a replacement alias:
    });
    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:
    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,
    );
    });
    ,
    export const threadSearchQuerySchema = z.object({
    query: z.string().trim().min(2),
    limitPerGroup: z.string().regex(/^\d+$/).optional(),
    });
    ,
    .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({
    ,
  • Plugin surfaces: sidebar-navigation can arrange or replace the Search action, thread-list explicitly keeps "the search action" as bb's, and the only plugin-side search() contract is the mention provider. Plugins receive sdk.threads (so they can call native search) but native search has no hook to call them:
    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",
    ,
    /** 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,
    ,
    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

  1. Active thread, initial alias: fixture thread whose messages do not contain the UUID; search(<full uuid>) returns the owning thread in active with a provider_thread_id match. Same for the first 8 characters.
  2. 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.
  3. Archived thread: both aliases return the thread in archived, not active.
  4. Stable thr_ navigation: every result carries the BB thread id; opening a result navigates to that thr_ id regardless of which alias matched; bb thread show <thr_id> and --resume-style flows are unchanged.
  5. Exclusions unchanged: deleted (deleted_at) and non-visible threads are never returned via an alias.
  6. Ranking and limits: alias matches rank above text matches; limitPerGroup and active/archived totals count alias-only threads correctly and compose with --project from Allow bb thread search to scope results to a project #2710.
  7. Backfill: a database that already has events.provider_thread_id values is searchable by every historical alias after migration, including aliases only present on archived threads.
  8. Plugin provider (if C is accepted): a test plugin returning a thread id for a query that matches no native segment yields a plugin match 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.
  9. Contract and CLI: bb thread search --json, the SDK threads.search, and the app search hook accept the new sourceKind values 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

  1. added theissue type on Sep 1, 2026
  2. added
    threads
    plugins
    confirmed-repro
    on Sep 1, 2026
  3. bb-slop-cop commented on Sep 1, 2026

    @bb-slop-cop
    Contributor

    🚨 SLOP COP 🚨 · new-issue-autopilot

    • Classification: Type Bug · Priority Medium · Effort High · labels threads, plugins, confirmed-repro.
    • Report: https://get-bb.github.io/reports/issues/2840.html
    • Verdict: REPRODUCED · root-cause confidence: high · reproduction label: confirmed-repro.
    • Root cause: Event writes store the provider identity, but the search index receives only message text. Native search queries only that index.
    • Reproduction: Two clean in-memory SQLite tests confirmed the stored identity, then received an empty thread search result.
    • Pull request: None. A safe fix needs a migration, stored-data changes, and a public contract decision.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmed-repropluginsthreads

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions