Skip to content

Add experimental sent-message editing - #1280

Merged
ymichael merged 9 commits into
mainfrom
bb/issue-1114-edit-messages
Aug 11, 2026
Merged

ymichael merged 9 commits into
mainfrom
bb/issue-1114-edit-messages

Conversation

@ymichael

@ymichael ymichael commented Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • add a default-off editMessages experiment enforced by both the app and server
  • let users edit any eligible completed message without changing history until submission
  • reuse the queued-message inline editor styling; opening the editor focuses it without selecting its contents
  • support Codex, Claude Code, and Pi through provider-native transcript checkpoints
  • expose the atomic edit through the SDK and bb thread edit-message
  • bump the host daemon protocol

Behavior

Opening or cancelling the inline editor is client-local and non-destructive. Submitting an edit stages provider history through the turn before the selected message, atomically replaces the selected conversation suffix, keeps workspace changes, and starts the edited turn.

Claude Code uses the latest assistant UUID with forkSession and upToMessageId. Pi records the session leaf entry and branches through it. Legacy Claude Code or Pi history without a checkpoint rejects safely when a retained turn is required.

Review hardening

  • hash external operation IDs before deriving provider staging identities, preventing Pi path-sanitization collisions
  • preserve and validate agent caller identity through the contract, CLI, edit service, persisted replacement turn, and permission policy
  • recheck queued messages, pending interactions, and the editable event high-water mark in the atomic rewrite transaction
  • keep the timeline edit handler stable so every cached row regains its action after an active turn becomes idle
  • let connected realtime own history-rewrite refreshes, retaining mutation invalidation only as the disconnected fallback
  • replace the thread-only search-segment index with (thread_id, source_seq) and add a generated migration plus exact query-plan coverage

Validation

  • cross-package typechecks across the app, server, runtime, CLI, SDK, contracts, daemon, plugin SDK, templates, database, domain, and thread view
  • full affected-package tests: 2,491 app tests, 1,400 server tests, and 857 agent-runtime tests, plus CLI, daemon, contracts, SDK, database, domain, and thread-view suites
  • app lint and generated plugin SDK/template checks
  • latest review-fix pass: 106 focused app/server/runtime/CLI tests, all 375 database tests, and 227 server-contract/SDK/plugin-SDK/template tests
  • all 10 directly affected Turbo typecheck tasks pass; lint reports no errors
  • credentialed standalone-dev-server QA passed through the source-built CLI for Codex, Claude Code, and Pi: editing an earlier message replaced the suffix, reran the edited turn, and preserved the replacement context on the next turn
  • Pi QA confirmed the rewind session was adopted as the canonical provider session without leaving an operation-suffixed staging file

The Pi smoke pass used openai-codex/gpt-5.6-luna because the configured Anthropic route was out of extra usage.

Simplification pass

  • omitting expectedRequestSequence on POST /edit-message now atomically edits the latest eligible message; the read-only GET /latest-message-edit route, threads.getLatestMessageEdit, and the CLI's GET-then-POST resolution are removed (the CLI's edit-latest is no longer racy)
  • staged rewind forks are keyed by the server-minted per-attempt leaseId: each attempt owns exactly one fork, which removes the cross-attempt lease refcounting, join validation, and staging-id hashing, drops operationId from both daemon rewind commands, and replaces the runtime's provider allowlist with the supportsFork capability
  • the edit service parses stored events through parseStoredEvent with type narrowing, reuses hasRootStoredTurnStarted, builds the rewind-prepare command with a destructure-rest spread, and resolves the editable-turn scan in one query
  • the queued and sent-message inline editors share one composer builder and one blocked-reason model; the inline-queued attachment path shares useDraftAttachmentUploads; one-caller helpers and redundant prop round-trips are inlined
  • render-wiring and duplicate tests were pruned across timeline actions, settings, CLI, and the Pi bridge
  • net effect: the PR's hand-written diff (excluding generated Drizzle snapshot/bundled types and the plan doc) is ~5,150 insertions, down from ~5,900 before the pass, with all affected typechecks and full test suites passing (server 1,426, app 2,508, agent-runtime 904, daemon 523, plus CLI/SDK/contracts/templates)

Related to #1114

@ymichael
ymichael force-pushed the bb/issue-1114-edit-messages branch from d469223 to 29ce093 Compare August 10, 2026 20:43
@ymichael
ymichael marked this pull request as ready for review August 10, 2026 20:43
@SawyerHood

Copy link
Copy Markdown
Collaborator

🚨 SLOP COP 🚨 · review

I am the SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and end-to-end behavior.

Comment thread packages/db/src/data/events.ts Resolved
Comment thread packages/agent-runtime/src/runtime.ts Resolved

@SawyerHood SawyerHood left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

ELI5: This feature lets a user change an old message. BB removes later chat events and asks the provider to answer again.

I found three defects that must be fixed before merge.

  • The edit waits for a host rewind without a shared thread lock. A send, queued message, or interaction can change state during that wait.
  • The edit API removes the agent caller identity. An agent can edit another root thread and start the replacement with user permission policy.
  • The API accepts any operation ID. Two different IDs can map to the same Pi session file and use the wrong checkpoint.

I also found six other defects.

  • Each prepared rewind keeps a provider session and two runtime entries until the daemon restarts.
  • The inline editor puts the caret at the end. It does not select the existing message.
  • A completed new turn restores the edit action only on the latest message. A page reload restores actions on earlier messages.
  • A connected client reloads history after realtime already reloads the same history.
  • The search suffix delete has no (threadId, sourceSeq) index. It can scan a full long-thread search history under the write lock.
  • The client does not check the active background-agent count. It can show an action that the server rejects.

The supported provider list also appears in the client, server, and runtime. A shared provider capability would reduce policy drift.

I tested the feature with the local app and a real Codex thread. A first-message edit worked, and an earlier edit removed the complete later suffix.

The final provider output was FINAL-REPLY. The removed secret and second turn were absent from the server timeline.

The five package type checks passed. The 68 focused app, server, and runtime tests passed.

@ymichael
ymichael force-pushed the bb/issue-1114-edit-messages branch 9 times, most recently from ad07b02 to 39654f5 Compare August 11, 2026 17:15
ymichael and others added 8 commits August 11, 2026 14:25
- fold latest-target resolution into POST /edit-message: omitting
  expectedRequestSequence atomically edits the latest eligible message,
  replacing the GET latest-message-edit route, SDK method, and the CLI's
  racy GET-then-POST two-step
- parse stored events through parseStoredEvent + type narrowing instead
  of hand-rolled JSON parsers, and reuse hasRootStoredTurnStarted
- build the rewind-prepare command with a destructure-rest spread,
  dropping the dead disallowedTools branch
- derive the request target kind from the staged fork instead of
  threading a redundant historyReplacement field
- reuse threadStartResultSchema for the identical prepare result shape
- migrate the inline-queued attachment path onto useDraftAttachmentUploads,
  inline the one-caller sentMessageEdit helpers, and drop the
  expectedRequestSequence round-trip and experiment-flag prop threading
  through the prompt area

Co-Authored-By: Claude Fable 5 <[email protected]>
- key staged rewind forks by the server-minted per-attempt leaseId:
  each attempt owns one fork, dissolving the cross-attempt lease
  refcount, join validation, cleanup-wait loop, and sha256 staging-id
  hashing, and dropping operationId from both daemon wire commands
- replace the runtime's hardcoded rewind provider allowlist with the
  existing supportsFork capability, share one staged-discard helper,
  and merge the preparing/prepared maps into a single lease-keyed map
- collapse the editable-turn candidate scan to one query
- share one inline-draft-composer builder between the queued and
  sent-message editors and fold the sent editor's bespoke blocked
  reasons into the queued editor's ready/unavailable precedent
- prune render-wiring and duplicate tests across timeline actions,
  settings, CLI, and the Pi bridge

Co-Authored-By: Claude Fable 5 <[email protected]>
@ymichael
ymichael force-pushed the bb/issue-1114-edit-messages branch from 9644f3c to fd28988 Compare August 11, 2026 21:28
@ymichael
ymichael merged commit 9699482 into main Aug 11, 2026
10 checks passed
@ymichael
ymichael deleted the bb/issue-1114-edit-messages branch August 11, 2026 21:35
ymichael added a commit that referenced this pull request Aug 12, 2026
## Motivation

The four provider adapters (claude-code, codex, pi, acp) and three
bridges carry near-verbatim copies of the same machinery: stdio harness,
session registry, adapter identity/command/translation boilerplate, turn
lifecycle, item-id scoping, and tool item translation. That duplication
has a measurable history of making cross-provider work slow and lossy:

- **Manual compaction (#1152)** landed through 19 commits, more than 11
of them iterating the same feature provider-by-provider ("Make OpenCode
ACP compaction reliable", "Avoid false Pi compaction success", "Show ACP
compaction lifecycle", "Fix compaction lifecycle races", ...). One
feature, re-fought per adapter.
- **Rate-limit normalization (#1027)** only ever shipped to 2 of 4
providers. On main today, `ProviderRateLimitState` is referenced by
claude-code and codex translation only — Pi and ACP have zero
references. Duplication didn't just slow the change down; it silently
dropped half the matrix.
- **`classifyExecutionSettingsChange` (#1236)** had to touch all four
adapters to change one provider's behavior, because the member wiring is
copied everywhere.

After this PR, the shared machinery lives in
`packages/agent-runtime/src/shared/` and a cross-provider change of this
kind is a one-place change.

## Honest accounting

Repo-wide this is roughly **−300 lines net** (2,204 insertions, 2,512
deletions, all inside `packages/agent-runtime`). The ~1,640-line figure
from the de-slop audit counts *duplicated* lines, not deletable ones —
extracting a shared implementation still costs its one copy plus
parameterization. The value of this PR is **one-place-change for
cross-provider behavior**, not raw deletion.

## Commit-by-commit review guide

The 8 commits are logically staged; each is independently revertable and
behavior-preserving:

1. **`fff1c494c` share bridge stdio harness** — the three bridges'
identical stdin/stdout JSON-RPC loop (readline wiring, dispatch, error
replies) moves to `shared/bridge-harness.ts`.
2. **`e1e7615ba` share bridge session registry** — the per-bridge
`Map`-of-sessions bookkeeping (create/get/stop/dispose) moves to
`shared/bridge-session-registry.ts`.
3. **`66fee1a30` share bridge environment helpers** — env-override
construction/parsing dedup in `shared/adapter-utils.ts` (round-trip
covered by a new test), plus `shared/mime-types.ts`.
4. **`6e6e9fbc1` share standard adapter members** — the biggest one.
Each adapter's copied identity/launch members, `initialize` plan,
unsupported-command fallbacks, accepted-command translation, model-list
parsing, and tool-call decoding collapse into
`createStandardAdapterMembers()` (`shared/standard-adapter-members.ts`);
adapters keep only their provider-specific `buildProviderCommandPlan`.
Review focus: confirm each adapter's per-command plans are unchanged
(they are moved, not edited).
5. **`4c6a3c65b` centralize provider turn hooks** — per-adapter
`ensureXTurnStarted` wrappers and the copied error-envelope-to-events
helper become `onTurnStart`/`onTurnFinish` hooks and `buildErrorEvents`
on the shared turn-state registry; `shared/provider-error-events.ts` is
deleted.
6. **`276516e32` share scoped item id factories** — the copied
open/completed scoped-item-id resolution moves to
`shared/scoped-item-ids.ts`.
7. **`fbd671c2a` share tool item translation** — the copied
toolUse/toolResult item builders move to
`shared/tool-item-translation.ts`.
8. **`86a313d7b` remove dead exports and helpers** — deletes exports and
helpers made unreferenced by the extractions (verified by repo-wide
typecheck).

## Wire compatibility (server ↔ host daemon)

**No `HOST_DAEMON_PROTOCOL_VERSION` bump needed, and none is included.**
The diff is confined to `packages/agent-runtime`;
`packages/host-daemon-contract` (session payloads, WS messages, host RPC
commands/results) is untouched and the protocol version stays at 106 on
both sides. The refactor changes where adapter/bridge code lives, not
what crosses the wire: the 900+ adapter tests that assert exact
translated `ThreadEvent` output (ids, scopes, payloads) pass without any
expectation changes, so the event stream the daemon posts to the server
is byte-identical.

## Rebase provenance

This branch originated in archived thread `thr_jyia7bkdqn` and was
rebased onto current main (original authorship preserved in the
commits). The rebase crossed #1280 (sent-message editing) and #1321
(provider-unhandled-event fix), both of which touched the same adapters;
conflicts were resolved by preserving main's shipped behavior and
re-grafting it into the extracted structure:

- `thread/discard` command plans re-added per provider (acp: noop,
claude-code: `thread/stop`, pi: `thread/discard`) inside each
`buildProviderCommandPlan`.
- Claude Code's `latestProviderCheckpointId` reset moved into the shared
`onTurnStart` hook (fires only for newly opened turns, same guard as the
removed wrapper).
- `sourceProviderCheckpointId` forwarding re-added to the claude-code
and pi `thread/fork` plans.

The rebase delta vs the original branch inside `packages/agent-runtime`
is exactly the sum of #1280 + #1321 (+1,124/−36), i.e. nothing from main
was lost and nothing beyond the refactor was introduced.

## Verification

- `pnpm exec turbo run typecheck` — whole repo, 58/58 tasks pass.
- `pnpm exec turbo run test --filter=@bb/agent-runtime` — 907 passed, 1
failed: `runtime.process-lifecycle.test.ts > bounds provider stderr
while data arrives without a newline`, which fails identically on
unmodified origin/main (reproduced during this work; also documented as
pre-existing in #1321). The lifecycle suites
(`runtime.lifecycle.test.ts` 28/28, `runtime.process-lifecycle.test.ts`
21/21 excluding the pre-existing failure) covering the Codex recovery
paths pass.
- `pnpm exec turbo run test --filter=@bb/host-daemon` (the only
dependent of `@bb/agent-runtime`) — 541/541 pass.

> AGENT GENERATED: by Claude Fable 5

🤖 Generated with [Claude Code](https://claude.com/claude-code)
ymichael added a commit that referenced this pull request Aug 12, 2026
The `editMessages` experiment shipped default-off in #1280. It is ready to
be on out of the box, with its existing Settings → Experiments toggle
becoming the opt-out rather than the opt-in.

Experiment defaults were derived as "every key is false", which left no way
to express a default-on experiment. `defaultExperiments` is now an explicit
per-key record typed as `Experiments`, so adding a key still fails to
compile until it declares a default.

Only unset keys read a default. `setExperiments` persists every key, so an
installation that has already saved any experiment toggle keeps its stored
`editMessages` value.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ymichael added a commit that referenced this pull request Aug 12, 2026
The `editMessages` experiment shipped default-off in #1280. It is ready to
be on out of the box, with its existing Settings → Experiments toggle
becoming the opt-out rather than the opt-in.

Experiment defaults were derived as "every key is false", which left no way
to express a default-on experiment. `defaultExperiments` is now an explicit
per-key record typed as `Experiments`, so adding a key still fails to
compile until it declares a default.

Only unset keys read a default. `setExperiments` persists every key, so an
installation that has already saved any experiment toggle keeps its stored
`editMessages` value.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
ymichael added a commit that referenced this pull request Aug 12, 2026
## Summary

Turns on the `editMessages` experiment out of the box. It keeps its
Settings → Experiments toggle — that just becomes the opt-out instead of
the opt-in.

Scoped to `editMessages` only. The Provider retry plugin default stays
off and can flip separately.

## Experiment defaults

`defaultExperiments` was derived as "every key is `false`", which left
no way to express a default-on experiment. It is now an explicit per-key
record typed as `Experiments`, so adding a key to `experimentKeys` still
fails to compile until it declares a default. No schema or persistence
change — experiment values already use key/value rows.

## Who this affects

Only unset keys read a default. `setExperiments` persists every key, so
an installation that has already saved any experiment toggle keeps its
stored `editMessages` value. Sent-message editing shipped in #1280, so
few installs have a persisted row yet; the rest pick up the new default.

Two `editMessages: false` sites are intentionally untouched — the
offline `unavailableSystemConfig` fallback in the app fails closed
independently of server defaults, and the desktop preload build test
stubs a fixed `/system/config` response.

## Discoverable surfaces

Updated `docs/configuration.md`, the `bb-cli` builtin skill, and the `bb
guide` threads/customization templates (regenerated), replacing the
"default-off" / "requires the experiment" wording.

## Validation

- `@bb/server` 1,436 tests, `@bb/app` 2,540 tests, `@bb/db` 379 tests,
`@bb/cli` 407 tests, plus `@bb/domain` and `@bb/templates`
- typecheck across server, app, domain, db, templates

One assertion needed updating: `test/system/experiments.test.ts`
hardcoded the old defaults.

No host daemon protocol bump: no wire shape, requiredness, or meaning
changed.

> AGENT GENERATED: by Claude Opus 5

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

Co-authored-by: Claude Opus 5 (1M context) <[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.

2 participants