Skip to content

Cache prepared statements for queue inspections - #8367

Merged
ymichael merged 7 commits into
mainfrom
slopcop/issue-8363
Dec 1, 2026
Merged

ymichael merged 7 commits into
mainfrom
slopcop/issue-8363

Conversation

@bb-slop-cop

@bb-slop-cop bb-slop-cop Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · new-issue-autopilot

Human comments

What was wrong

Four fixed-shape database queue inspections rebuilt their Drizzle queries and prepared synchronous SQL on every invocation instead of reusing the existing connection-local statement cache. The focused regression observed 40 native preparations for 40 reads in each path on trusted main, reproduced again in a second clean checkout.

Report: https://get-bb.github.io/reports/issues/8363.html

What changed

  • Cache stable placeholder statements for live queues, claimed queues, manual-stop pauses, and wait-kind inspections.
  • Retain query predicates, ordering, transaction behavior, and the shared manual-stop subquery builder.
  • Update the existing query-plan allowlist caller to the prepared builder; add no new exception.
  • Database subsystem only: two source files. No dependency, generated-file, migration, persisted-data, public protocol, or CLI changes.

How you verified

  • Before the production fix: four focused regressions fail on trusted origin/main at b0ddaad731565d7e4de68d824120d802fc78f7d5, each observing 40 preparations instead of one. The same test fails for the same reason in a second clean trusted checkout.
  • pnpm exec turbo run test typecheck lint:type-aware --filter=@bb/db passes: 766 tests across 73 files, typecheck, and type-aware lint.
  • Real server (pnpm start:worktree, Codex thread with one slow turn and five queued follow-ups): before, the four functions prepared 35 times per 6-turn drain; after, once each on the first drain and zero on the second, reusing the per-connection prepareCachedQuery cache.
  • The fixed prepare-count test was dropped in review: exact-count budgets fail on legitimate changes.

Fixes #8363

AGENT GENERATED

@blacksmith-sh

This comment has been minimized.

@blacksmith-sh

This comment has been minimized.

@ymichael
ymichael merged commit c0394a5 into main Dec 1, 2026
35 checks passed
@ymichael
ymichael deleted the slopcop/issue-8363 branch December 1, 2026 00:51
ymichael added a commit that referenced this pull request Dec 1, 2026
## Human comments

## What was wrong

Six of the timeline window readers in `packages/db/src/data/events.ts`
built a fresh Drizzle query on every call, so each thread open and
scroll-back recompiled their SQL and re-prepared the SQLite statement on
the server's main thread: the budget floor, root turns, thread window,
notices (#8439), plus the byte-budget floor and turn rows. Only
`advanceTimelineWindowBudgetFloorSequence` and
`listStoredTimelineWindowEventRows` reused a cached statement.

## What changed

- The budget floor, root turns, thread window and notices readers use
`prepareCachedQueryVariant`, the same path as their two cached siblings
(and #8367's queue queries). Thread ID, sequence bounds and the budget
offset are bound parameters. The cache key holds only the shape
dimensions: output limit, whether there is an upper bound, the
diagnostic filter, and the excluded types.
- `findStoredTimelineWindowByteBudgetFloor` and
`listStoredTimelineTurnEventRows` reuse a cached raw better-sqlite3
statement (`prepareCachedRawStatement`). That keeps the byte floor
streaming rows and stopping early, and keeps turn rows' unmapped reads.
Turn IDs bind as one JSON array through `json_each` instead of a
per-length `IN (?, …)` list. The plan is unchanged: `SEARCH events USING
INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND
turn_id=?)`.
- The readers share one `storedTimelineWindowPlaceholderConditions`
helper.
- The regression tests live in `events-preparation.test.ts`, next to the
other cached-read tests.

No wire, CLI, schema or stored-data changes.

## How you verified

- The issue's repro script on main: 10 warm calls cause 10 statement
preparations for each of the four readers. On this branch: 0.
- Real data: a `VACUUM INTO` snapshot of a production `bb.db` (3.8 GB),
on the 30 threads with the most events. Main's and this branch's
`events.ts` were loaded in one process and alternated per batch (CPU
time, median of 20–30 batches). Rows are identical for every thread.

  | Reader | main | branch | saved |
  |---|---|---|---|
  | budget floor (1,500-event budget) | 903µs | 806µs | 97µs |
  | budget floor ("has older" check) | 136µs | 40µs | 97µs |
  | root turns | 755µs | 645µs | 110µs |
  | thread window | 320µs | 138µs | 182µs |
  | notices | 289µs | 79µs | 210µs |
  | byte-budget floor | 1,389µs | 1,263µs | 126µs |
  | turn rows (1–37 turns) | 5,965µs | 4,806µs | 1,159µs |

A real `buildThreadTimelineWithProfile` latest page plus one older page
prepares 22.9 statements on the first commit versus 33.6 on main.
Whole-build wall-clock times on that host were dominated by unrelated
load, so this PR reports per-reader CPU time.
- Tests: for each of the six readers, a test reads several window
shapes, a second thread and narrower bounds, then asserts identical
results with zero `sqlToQuery` compilations and zero `prepare` calls. A
second test checks that output-limit variants stay apart in the row
readers. Two mutations fail these tests: inlining the bound values into
the cached byte floor, and dropping the output limit from the turn-rows
key.
- `pnpm exec turbo run typecheck lint lint:type-aware test
--filter=@bb/db`: typecheck and lint pass, and 788 tests pass. Locally,
`queued-message-state.test.ts` and `queued-thread-messages.test.ts` fail
the query-plan guard on `isThreadQueueAutoSendPaused`. That code is
untouched, and the failure also happens with main's `events.ts`.
- `pnpm exec turbo run test --filter=@bb/server --
test/services/threads/`: 385 tests pass. `issue-2677-repro.test.ts`
fails locally on the same queue query-plan guard, also with main's
`events.ts`.

Fixes #8439

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: SawyerHood <[email protected]>
Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Dec 1, 2026
## Human comments

## What was wrong

`packages/db/src/query-plan-test-guard.ts` attributed a query to its
caller at two different moments. With `BB_QUERY_PLAN_EXECUTED` or
`BB_QUERY_PLAN_REPORT` set (CI sets `BB_QUERY_PLAN_EXECUTED`), it read
the stack when the statement was prepared; without them (local runs), it
read the stack when the statement ran. Drizzle prepares ordinary queries
on every call, so both moments usually agree. A `prepareCachedQuery`
statement is prepared inside its builder and run from the outer
function, so the modes disagree. #8367 (c0394a5) cached
`isThreadQueueAutoSendPaused` and renamed its allowlist entry to
`prepareIsThreadQueueAutoSendPaused`, the name only CI produces. Since
then, a plain local `pnpm exec turbo run test --filter=@bb/db` fails at
file teardown in `queued-thread-messages.test.ts` /
`queued-message-state.test.ts` with a `correlated-subquery on events in
...#isThreadQueueAutoSendPaused` violation, and about 37 `@bb/server`
test files fail the same way.

The production auditor (`observeFirstExecution`, enabled by
`BB_QUERY_PLAN_AUDIT`) also reads the stack at run time, and
`docs/debugging-and-qa.md` defines `caller` as the function that ran the
query. CI's prepare-time attribution was the odd one out, and the
production audit has been warning on this allowlisted query since #8367.

## What changed

- `packages/db/src/query-plan-test-guard.ts`: the caller is read when
the statement runs, and only when its plan has a finding, in every mode
(one stack depth, 40; local runs used 10 before). This keeps attribution
identical locally, in CI, and in the production auditor. With
`BB_QUERY_PLAN_EXECUTED`/`BB_QUERY_PLAN_REPORT`, the executed query
functions are still recorded when a statement is prepared, as before. A
cached statement is prepared inside the function that first runs it, so
that function is still credited.
- `packages/db/src/query-plan-guard.ts`: `QueryPlanAuditor.observe`
(eager caller) is removed; nothing calls it anymore.
- `packages/db/src/query-plan-allowlist.ts`: the entry is renamed back
to `queued-thread-messages.ts#isThreadQueueAutoSendPaused`. No new
entry.
- `packages/db/test/query-plan-test-guard.test.ts`: the subprocess test
runs a cached query (`isThreadQueueAutoSendPaused`) under the local,
executed-functions, and report modes. It asserts no violations in the
first two, that every report finding names
`#isThreadQueueAutoSendPaused` and is allowed, and that the executed
output lists the running functions.

This doesn't change the CLI, the wire protocol, or the docs. This brings
the guard in line with what the docs already describe.

### Cost in CI mode

I measured stack reads with an instrumented guard over the full suites
with `BB_QUERY_PLAN_EXECUTED` set. CPU is summed across workers.

| | `@bb/server` stack reads | CPU | `@bb/db` stack reads | CPU |
|---|---|---|---|---|
| main (prepare-time caller) | 952k | 56 s | 245k | 8.5 s |
| first commit (stack read on every run) | 2.47M | 115 s | 428k | 21.7 s
|
| this PR (prepare-time recording + lazy run-time caller) | 1.03M (956k
prepare + 76k caller) | 48.5 s | 246k | 7.5 s |

Reading the stack on every run credited no additional query function; it
only dropped 46 private `prepare*` builder names. So the second commit
goes back to prepare-time recording.

## How you verified

- Without the fix, the new test fails: local mode reports three
violations on `#isThreadQueueAutoSendPaused`. With the fix, it passes.
- `pnpm exec turbo run test typecheck --filter=@bb/db
--filter=@bb/server` with no query-plan env vars: passes.
- `BB_QUERY_PLAN_EXECUTED=.query-plan/executed.jsonl pnpm exec turbo run
test --filter=@bb/db --filter=@bb/server`: passes, and `executed.jsonl`
is written for both packages.
- Query Plan Audit path: `BB_QUERY_PLAN_REPORT=<file>` over the same
suites passes, then `pnpm --filter @bb/db check:query-plan-report
<file>` prints "Query plan report matches the allowlist (855 findings)
and runs all 554 query functions."
- Earlier runs on the first commit saw
`apps/server/test/app/install-machine-script.test.ts` time out while
host load average was 43–77. That file doesn't touch the database,
passes 56/56 alone, and passed in all runs on this commit.
- oxlint and prettier pass on the changed files.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
scowalt pushed a commit to scowalt/bb that referenced this pull request Dec 1, 2026
🚨 **SLOP COP** 🚨 · `new-issue-autopilot`

## Human comments

## What was wrong

Four fixed-shape database queue inspections rebuilt their Drizzle
queries and prepared synchronous SQL on every invocation instead of
reusing the existing connection-local statement cache. The focused
regression observed 40 native preparations for 40 reads in each path on
trusted main, reproduced again in a second clean checkout.

Report: https://get-bb.github.io/reports/issues/8363.html

## What changed

- Cache stable placeholder statements for live queues, claimed queues,
manual-stop pauses, and wait-kind inspections.
- Retain query predicates, ordering, transaction behavior, and the
shared manual-stop subquery builder.
- Update the existing query-plan allowlist caller to the prepared
builder; add no new exception.
- Database subsystem only: two source files. No dependency,
generated-file, migration, persisted-data, public protocol, or CLI
changes.

## How you verified

- Before the production fix: four focused regressions fail on trusted
`origin/main` at `a8c32288cf24894fbe85cb3a9ca0469c7a997ed6`, each
observing 40 preparations instead of one. The same test fails for the
same reason in a second clean trusted checkout.
- `pnpm exec turbo run test typecheck lint:type-aware --filter=@bb/db`
passes: **766 tests across 73 files**, typecheck, and type-aware lint.
- Real server (`pnpm start:worktree`, Codex thread with one slow turn
and five queued follow-ups): before, the four functions prepared 35
times per 6-turn drain; after, once each on the first drain and zero on
the second, reusing the per-connection `prepareCachedQuery` cache.
- The fixed prepare-count test was dropped in review: exact-count
budgets fail on legitimate changes.

Fixes get-bb#8363

> AGENT GENERATED

<!-- slopcop:rule=new-issue-autopilot run=run_qvlv91nlmx27hlre
sha=issue-8363 kind=summary -->

---------

Co-authored-by: SawyerHood <[email protected]>
Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
scowalt pushed a commit to scowalt/bb that referenced this pull request Dec 1, 2026
## Human comments

## What was wrong

Six of the timeline window readers in `packages/db/src/data/events.ts`
built a fresh Drizzle query on every call, so each thread open and
scroll-back recompiled their SQL and re-prepared the SQLite statement on
the server's main thread: the budget floor, root turns, thread window,
notices (get-bb#8439), plus the byte-budget floor and turn rows. Only
`advanceTimelineWindowBudgetFloorSequence` and
`listStoredTimelineWindowEventRows` reused a cached statement.

## What changed

- The budget floor, root turns, thread window and notices readers use
`prepareCachedQueryVariant`, the same path as their two cached siblings
(and get-bb#8367's queue queries). Thread ID, sequence bounds and the budget
offset are bound parameters. The cache key holds only the shape
dimensions: output limit, whether there is an upper bound, the
diagnostic filter, and the excluded types.
- `findStoredTimelineWindowByteBudgetFloor` and
`listStoredTimelineTurnEventRows` reuse a cached raw better-sqlite3
statement (`prepareCachedRawStatement`). That keeps the byte floor
streaming rows and stopping early, and keeps turn rows' unmapped reads.
Turn IDs bind as one JSON array through `json_each` instead of a
per-length `IN (?, …)` list. The plan is unchanged: `SEARCH events USING
INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND
turn_id=?)`.
- The readers share one `storedTimelineWindowPlaceholderConditions`
helper.
- The regression tests live in `events-preparation.test.ts`, next to the
other cached-read tests.

No wire, CLI, schema or stored-data changes.

## How you verified

- The issue's repro script on main: 10 warm calls cause 10 statement
preparations for each of the four readers. On this branch: 0.
- Real data: a `VACUUM INTO` snapshot of a production `bb.db` (3.8 GB),
on the 30 threads with the most events. Main's and this branch's
`events.ts` were loaded in one process and alternated per batch (CPU
time, median of 20–30 batches). Rows are identical for every thread.

  | Reader | main | branch | saved |
  |---|---|---|---|
  | budget floor (1,500-event budget) | 903µs | 806µs | 97µs |
  | budget floor ("has older" check) | 136µs | 40µs | 97µs |
  | root turns | 755µs | 645µs | 110µs |
  | thread window | 320µs | 138µs | 182µs |
  | notices | 289µs | 79µs | 210µs |
  | byte-budget floor | 1,389µs | 1,263µs | 126µs |
  | turn rows (1–37 turns) | 5,965µs | 4,806µs | 1,159µs |

A real `buildThreadTimelineWithProfile` latest page plus one older page
prepares 22.9 statements on the first commit versus 33.6 on main.
Whole-build wall-clock times on that host were dominated by unrelated
load, so this PR reports per-reader CPU time.
- Tests: for each of the six readers, a test reads several window
shapes, a second thread and narrower bounds, then asserts identical
results with zero `sqlToQuery` compilations and zero `prepare` calls. A
second test checks that output-limit variants stay apart in the row
readers. Two mutations fail these tests: inlining the bound values into
the cached byte floor, and dropping the output limit from the turn-rows
key.
- `pnpm exec turbo run typecheck lint lint:type-aware test
--filter=@bb/db`: typecheck and lint pass, and 788 tests pass. Locally,
`queued-message-state.test.ts` and `queued-thread-messages.test.ts` fail
the query-plan guard on `isThreadQueueAutoSendPaused`. That code is
untouched, and the failure also happens with main's `events.ts`.
- `pnpm exec turbo run test --filter=@bb/server --
test/services/threads/`: 385 tests pass. `issue-2677-repro.test.ts`
fails locally on the same queue query-plan guard, also with main's
`events.ts`.

Fixes get-bb#8439

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: SawyerHood <[email protected]>
Co-authored-by: Michael Yong <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
scowalt pushed a commit to scowalt/bb that referenced this pull request Dec 1, 2026
…-bb#8466)

## Human comments

## What was wrong

`packages/db/src/query-plan-test-guard.ts` attributed a query to its
caller at two different moments. With `BB_QUERY_PLAN_EXECUTED` or
`BB_QUERY_PLAN_REPORT` set (CI sets `BB_QUERY_PLAN_EXECUTED`), it read
the stack when the statement was prepared; without them (local runs), it
read the stack when the statement ran. Drizzle prepares ordinary queries
on every call, so both moments usually agree. A `prepareCachedQuery`
statement is prepared inside its builder and run from the outer
function, so the modes disagree. get-bb#8367 (4f35332) cached
`isThreadQueueAutoSendPaused` and renamed its allowlist entry to
`prepareIsThreadQueueAutoSendPaused`, the name only CI produces. Since
then, a plain local `pnpm exec turbo run test --filter=@bb/db` fails at
file teardown in `queued-thread-messages.test.ts` /
`queued-message-state.test.ts` with a `correlated-subquery on events in
...#isThreadQueueAutoSendPaused` violation, and about 37 `@bb/server`
test files fail the same way.

The production auditor (`observeFirstExecution`, enabled by
`BB_QUERY_PLAN_AUDIT`) also reads the stack at run time, and
`docs/debugging-and-qa.md` defines `caller` as the function that ran the
query. CI's prepare-time attribution was the odd one out, and the
production audit has been warning on this allowlisted query since get-bb#8367.

## What changed

- `packages/db/src/query-plan-test-guard.ts`: the caller is read when
the statement runs, and only when its plan has a finding, in every mode
(one stack depth, 40; local runs used 10 before). This keeps attribution
identical locally, in CI, and in the production auditor. With
`BB_QUERY_PLAN_EXECUTED`/`BB_QUERY_PLAN_REPORT`, the executed query
functions are still recorded when a statement is prepared, as before. A
cached statement is prepared inside the function that first runs it, so
that function is still credited.
- `packages/db/src/query-plan-guard.ts`: `QueryPlanAuditor.observe`
(eager caller) is removed; nothing calls it anymore.
- `packages/db/src/query-plan-allowlist.ts`: the entry is renamed back
to `queued-thread-messages.ts#isThreadQueueAutoSendPaused`. No new
entry.
- `packages/db/test/query-plan-test-guard.test.ts`: the subprocess test
runs a cached query (`isThreadQueueAutoSendPaused`) under the local,
executed-functions, and report modes. It asserts no violations in the
first two, that every report finding names
`#isThreadQueueAutoSendPaused` and is allowed, and that the executed
output lists the running functions.

This doesn't change the CLI, the wire protocol, or the docs. This brings
the guard in line with what the docs already describe.

### Cost in CI mode

I measured stack reads with an instrumented guard over the full suites
with `BB_QUERY_PLAN_EXECUTED` set. CPU is summed across workers.

| | `@bb/server` stack reads | CPU | `@bb/db` stack reads | CPU |
|---|---|---|---|---|
| main (prepare-time caller) | 952k | 56 s | 245k | 8.5 s |
| first commit (stack read on every run) | 2.47M | 115 s | 428k | 21.7 s
|
| this PR (prepare-time recording + lazy run-time caller) | 1.03M (956k
prepare + 76k caller) | 48.5 s | 246k | 7.5 s |

Reading the stack on every run credited no additional query function; it
only dropped 46 private `prepare*` builder names. So the second commit
goes back to prepare-time recording.

## How you verified

- Without the fix, the new test fails: local mode reports three
violations on `#isThreadQueueAutoSendPaused`. With the fix, it passes.
- `pnpm exec turbo run test typecheck --filter=@bb/db
--filter=@bb/server` with no query-plan env vars: passes.
- `BB_QUERY_PLAN_EXECUTED=.query-plan/executed.jsonl pnpm exec turbo run
test --filter=@bb/db --filter=@bb/server`: passes, and `executed.jsonl`
is written for both packages.
- Query Plan Audit path: `BB_QUERY_PLAN_REPORT=<file>` over the same
suites passes, then `pnpm --filter @bb/db check:query-plan-report
<file>` prints "Query plan report matches the allowlist (855 findings)
and runs all 554 query functions."
- Earlier runs on the first commit saw
`apps/server/test/app/install-machine-script.test.ts` time out while
host load average was 43–77. That file doesn't touch the database,
passes 56/56 alone, and passed in all runs on this commit.
- oxlint and prettier pass on the changed files.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael added a commit that referenced this pull request Dec 1, 2026
## Human comments

## What was wrong

`slots.messageAction` had no way to say which messages an action works
on, so every plugin action showed on every user and assistant message.
Conductor's "Fork to new workspace" and Side chat's "Reply in side chat"
showed on user messages, and Conductor's fork also showed on threads
that cannot fork. `ThreadChatProps.messageActions` was a second shape
for the same thing, with `roles` and a `run(message)` that got no
thread, panel, composer or selection. bb's own Copy, Edit, Copy link,
Add to chat and Fork could not have been built on the slot: they were
hand-wired into `MessageActionBar` and `TimelineSelectionMenu` with
their own role rules, availability, streaming state and placement. This
closes audit finding a-thread F4 and core-contributions rank 10.

## What changed

Message actions now use the model thread actions already use: an
optional `useData` hook per timeline, and a pure `item` per message that
returns the action or null. bb's five actions are ordinary registrations
on that model, using only the public SDK.

**Slot contract** (`packages/plugin-sdk/src/app-contract.ts`, SDK
0.6.215):

- `PluginMessageActionRegistration<Data>` adds:
- `experimental_useData?({ threadId }): Data`. A React hook bb calls
once per mounted timeline with that timeline's thread, never per
message. Plugins read thread facts there with `experimental_useThread`
and return only what `item` needs.
- `experimental_item?(input)`: pure and synchronous, called per message
while rendering. Returns null or `{ label, icon?, disabled?, run({
invokedFrom, confirm }) }`.
- `experimental_selectionItem?(input)`: the same for text selected in an
assistant message. Its input adds `selection: { text, markdown }`.
  - `experimental_placement?: "inline" | "menu"` (default `"inline"`).
- `experimental_group?: string` and `experimental_order?: number`. The
row, its overflow menu and the selection menu sort by group (string
compare; unset sorts after every group), then order within the group
(ascending; unset last), then registration order with bb's own first:
the rule thread actions use with `group` and `order`.
`experimental_MESSAGE_ACTION_GROUPS` exports bb's groups: `copy` (Copy
link 10, Copy 20), `edit` (Edit 10), `compose` (Add to chat 10, row menu
and selection menu) and `branch` (Fork 10). The group is optional,
unlike other slots', because `slots.messageAction` is stable and its
run-only form predates groups. Groups only order actions; the menus draw
no separator.
- `run` returns `void` like every other plugin action. Calling
`confirm()` shows a check mark on the inline button for 2 s; it does
nothing from a menu. bb's Copy calls it after a successful copy.
- The item input (`ExperimentalMessageActionItemInput<Data>`) is the
callback context plus `message`, `requestEdit` and `data`. `composer` is
the composer of the message's thread on this surface. `requestEdit`
opens bb's inline sent-message editor and is null where bb would not
offer Edit. There are no fork flags: a fork action computes its
availability in `useData`.
- The original run-only form (`{ id, title, icon?,
experimental_surfaces?, run }`) still works and shows where it always
did. A registration mixing `run` with `item` or `selectionItem` fails
registration.
- New `experimental_appendQuoteToDraft(draft, text, attachments?)` on
`@get-bb/plugin-sdk/app`: bb's Add to chat quoting, pure, for
`composer.replace`. Its implementation moved from client-core into the
SDK's composer draft transforms. bb's message Add to chat, the diff,
file-preview and terminal Add to chat, root compose's quote, the retired
`composer.addQuote` and the test harness all run that one copy.
- `ThreadChatMessageReference` adds `experimental_settled`,
`experimental_attachments` (`ComposerAttachment[]`) and
`experimental_imageUrls`. `ExperimentalClipboardContent` adds
`imageUrl`, copied through bb's own image clipboard writer.
- `ThreadChatProps.experimental_messageActions` takes item-form
registrations (without `experimental_surfaces` or
`experimental_useData`) for one embedded chat.
- `ThreadChatProps.messageActions` and `ThreadChatMessageAction` are
removed from the types, docs and test harness. Compiled plugins that
still pass the prop keep working: `PluginThreadChat` adapts each entry
into an inline item that returns null outside its roles, and warns once
per plugin.

**Core on the shared path:**

- `apps/app/src/core-contributions/message-actions.ts` registers Copy
link, Copy, Edit, Add to chat (row menu), Add to chat (selection menu)
and Fork through `definePluginApp`, with public SDK imports only.
- Add to chat is `composer.replace((d) =>
experimental_appendQuoteToDraft(d, text, attachments))`, then
`composer.focus()`.
- Fork's `useData` reads `experimental_useThread` and
`experimental_useProviders` and returns whether the thread has an
environment, is not archived and its provider supports forking. Its
`item` offers Fork on assistant messages when that is true and the
surface has a composer. Running it is `sdk.threads.fork({
sourceThreadId, sourceSeqEnd, origin: "app" })` then
`navigate.toThread`, once per click, with bb's error toast on failure.
It replaces `useForkThreadFromMessage` and client-core's
`isThreadForkable`.
- `MessageActionCollectors` (`apps/app/src/components/plugin/`) runs
each registration's `useData` for the timeline. `ThreadTimelineRows`
holds the values and passes them through a context. Rows hand
`MessageActionBar` their action source, and the bar resolves its own
actions. So a new `useData` value re-renders the action bars, not the
message content.
- `lib/plugin-message-actions.ts` `buildMessageActions` resolves items,
placement and order for the row and the selection menu.
`MessageActionBar` and `TimelineSelectionMenu` render only that list.
`TimelineSelectionMenu` keeps its `onAddToChat` path for the diff,
file-preview and terminal selection menus, which are not message
actions.
- `ConversationMessageContent`, `ThreadTimelineRows`,
`ThreadTimelineSurface`, `ThreadScreen`, `ThreadDetailView` and
`PluginThreadChat` drop the per-action props and the `canFork` /
`canSpawnChild` plumbing.
- The plugin-bound `sdk.threads.fork` puts the new thread in the app's
cache before the caller navigates, as bb's button did. It imports the
thread cache owner on demand to keep it out of the boot payload.
- bb's message action registrations load with the timeline, as bb's
hand-wired actions did on main: `useSurfaceMessageActionSlots`
(`lib/message-action-surface.tsx`) puts them ahead of the plugin slots
instead of the plugin slot store collecting them at boot.
`experimental_useProviders` also moves from `plugin-sdk-hooks.ts` into
its own `provider-directory-state.ts`; importing it from
`plugin-sdk-hooks.ts` had pulled that whole module and its imports into
the boot payload (32 KB raw over main).

**Server fork changes (every caller of `POST /api/v1/threads/fork`):**

- A fork takes the model and reasoning level chosen in the source's
model picker, falling back to its last turn's (`thread-fork.ts` resolves
the source's next-turn execution plan).
- A visible fork goes into the source's section, and is pinned if the
source is. A hidden fork, such as Side chat's, gets neither, because it
has no place in the sidebar. Before, only bb's button copied section and
pin, so Conductor, the SDK and `bb thread fork` now do too.
- A thread at the nesting limit can be forked. #85 ran the child-nesting
depth check on fork sources so that forks and side chats would "consume
the same spawn allowance" as `canSpawnChild`. But a fork has no parent,
so it never deepens the tree. An agent at the limit can already create
top-level threads with `bb thread spawn`. The check only stopped bb's
Fork, Side chat and Conductor working in threads four levels deep. The
other source checks (missing, other project, archived, deleted) stay.

**Queued-message edit:** message actions get the composer of the
message's own thread on that surface, including the inline editor of one
of its queued messages while that is open. So during a queued-message
edit, Add to chat quotes into that edit instead of the main draft.
Before, it disappeared while the edit was open.

**First-party callers:**

- Side chat: "Reply in side chat" is an assistant-only `item` and
`selectionItem`. "Send to main thread" moves to
`experimental_messageActions`.
- Conductor: "Fork to new workspace" is an assistant-only `item`, with
the same fork check as bb's Fork in its own `useData`. Its `run` reads
the source thread with `sdk.threads.get`.
- Both raise `engines.bbPluginSdk` to `>=0.6.215`.

**Docs:**

- `docs/api_to_audit.md`: the message-action entry (contract, core and
plugin callers, the fork and Add to chat paths, the retired prop, audit
questions) and a new `experimental_appendQuoteToDraft` entry.
- The Plugin Guide message-actions card
(`plugins/plugin-api-docs/src/surfaces.ts`).
- The bb-plugin-authoring references `frontend-renderer-slots.md` and
`frontend-components.md`.
- The `bb thread fork` guide describes the model, section and pin a fork
takes.

**Visible differences from main:**

- Plugin actions now show only on the messages their `item` returns an
action for. Side chat and Conductor are assistant-only, and Conductor's
fork is hidden where the thread cannot fork.
- Inline Edit and plugin buttons share Copy's hover transition and
`focus-visible` opacity, because Copy is now an ordinary action button.
No positions move.
- bb's Fork is no longer greyed out in threads at the nesting limit; it
works there.
- Forks from the CLI, SDK and plugins follow the source's picker choice,
section and pin (above).
- Add to chat during a queued-message edit quotes into that edit
(above).
- The message "…" menu is non-modal, as thread action menus are. On main
its focus trap pulled focus back from the composer that Add to chat had
just focused, so focus fell to the page when the menu closed; now it
stays in the composer, as it does from the selection menu.

**Community callers (not edited):**

- `slots.messageAction` in the run-only form: brsbl timeline-comments;
vburojevic handoff and linear; rebryk bookmarks; and about 20 more in
the corpus. All keep today's behavior.
- `ThreadChatProps.messageActions`: brsbl desktop, robdodson
side-chat-links, xMinor-1 sticker-note, cristoslc focus-board and
anirudhranganath thread-tabs. Their compiled code keeps working through
the adapter and gets a one-time warning; rebuilding against SDK 0.6.215
needs `experimental_messageActions`.

## How you verified

- New or changed tests that fail on main:
  - `ThreadTimelineRows.actions.test.tsx`:
- `item` runs per message with that message's input; its action runs
with `invokedFrom` and `confirm`, and `confirm()` turns the inline
button into a check mark
- `useData` runs once for the timeline with its `threadId`; items
re-evaluate when its value changes, and it unsubscribes on unmount
- bb's Fork is offered only with a composer, on an unarchived thread
with an environment whose provider can fork
- bb's Fork calls `sdk.threads.fork` once at a time; a rejected fork
stays on the source and can be retried, and the retry opens the fork
    - inline order and menu placement of plugin actions among bb's own
- a selection-only action after bb's Add to chat, with the selection's
Markdown
- `experimental_messageActions` with the full item input, and retired
`messageActions` filtered by role
- message actions get only their own thread's composer, including its
queued-message editor
- Add to chat (row, for user and assistant messages with files, and
selection) writes the quote into the draft and focuses the composer
- `MessageActionBar.test.tsx`: an inline run that confirms shows a check
mark and ignores clicks meanwhile; the menu invocation and disabled
rows. Both check-mark tests fail if the bar stops passing `confirm`.
- `MessageActionBar.test.tsx`: a menu row whose `run` focuses another
element keeps that focus after the menu closes; fails with the modal
menu (focus ends on `<body>`).
- `plugin-app-message-action.test.ts`: defaults and validation for the
item form.
- `public-thread-fork.test.ts`: a fork takes the source's picker model
and reasoning over its last turn's. A visible fork takes the source's
section and pin and a hidden fork takes neither; the hidden half fails
on the previous route with `expected 'sec_…' to be null`.
- `thread-create-seed-without-run.test.ts`: a thread at the nesting
limit forks into a top-level thread.
- `plugin-bound-sdk.test.ts`: a plugin fork is in the thread cache
before the caller navigates.
- `PluginThreadChat.test.tsx`: a retired `messageActions` list still
runs and warns once.
- The existing row-isolation guard
(`ThreadTimelineRows.row-isolation.test.tsx`) still sees each row render
once on mount with per-timeline `useData`.
- After rebasing on `a6e31224a29`:
- `pnpm exec turbo run typecheck lint --filter='...[origin/main]'`: 167
of 167 tasks pass.
- Tests pass for app (7553), plugin SDK (512), Plugin Guide cards (76),
Plugin Guide skill docs (15), Conductor (30) and Side chat (27).
- `public-thread-fork.test.ts` and
`thread-create-seed-without-run.test.ts`: 62 of 62 pass. Locally both
files still fail at teardown on main's query-plan guard bug (below);
with CI's `BB_QUERY_PLAN_EXECUTED` set they pass.
- On the previous base (`5be1d105359`), `pnpm exec turbo run test
--filter='...[origin/main]'` passed apart from two causes unrelated to
this branch:
- `isThreadQueueAutoSendPaused` (from #8367) trips the query-plan guard
at file teardown in local runs only: the guard names the caller where
the statement runs locally but where it is prepared in CI, and the
allowlist names `prepareIsThreadQueueAutoSendPaused`. A clean
`origin/main` checkout fails the same way. Every test in those files
passes.
- Timeouts and a temp-file race under the full parallel run
(`install-machine-script`, the Guide's `plugin-authoring-docs`,
storage-retention, the provider-literal ratchet, host-daemon
`injected-skills`, 3 integration files) pass when re-run alone.
- Live, on `pnpm start:worktree` with Codex turns and Side chat and
Conductor installed:
- In headed Chrome, Add to chat from the "…" menu (user and assistant
messages) and from the selection menu each leave focus in the composer
with the caret on a new line below the quote; before the menu change,
the "…" path left focus on `<body>`.
- bb's Fork into new thread from an assistant message opens the fork
("Forked from ok").
- From a pinned source in a section: Conductor's "Fork to new workspace"
creates a new worktree thread that is pinned and in that section. Side
chat's "Reply in side chat" (from two different messages) creates hidden
forks that are neither pinned nor sectioned.
- Before "Copy the source's section and pin only into visible forks", a
Side chat fork from that source came out pinned and sectioned.
- The row, menu, selection-menu and 390 px touch-drawer parity checks
from the first four commits (with real Claude Code turns) still describe
what renders; the later commits change how actions are computed, not
where they render.
- `check-bundle-budget.mjs` on a local production build of
`b6a39273c9d`: boot payload 1667.4 KB raw / 418.5 KB brotli against
main's 1665.1 / 417.8 at `a6e31224a29` (budget 1682.1 / 419.1). Against
current main the boot payload grows only by this PR's registration
validation (+2.7 KB raw), Add to chat's quoting with attachments (net
+0.55 KB), the plugin fork's cache insert (+0.65 KB) and image copy
(+0.1 KB).
- Measured on a production build with a 32-row Codex thread, sending one
turn: 80 message-row renders and 42 ms of timeline rendering. The
thread's bookkeeping updates during the turn (turn start, turn end,
mark-read) re-ran Fork's `useData` but re-rendered no rows. The branch's
earlier design, which passed the thread in the item input, did 183
renders and 113 ms on a similar turn. I did not measure main.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

db: hot-path queue-drain queries in queued-thread-messages.ts block the main event loop 17×–27× longer by recompiling multi-alias SQL on every call

2 participants