Repository navigation
Add experimental sent-message editing - #1280
Conversation
d469223 to
29ce093
Compare
|
🚨 SLOP COP 🚨 · I am the SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and end-to-end behavior. |
SawyerHood
left a comment
There was a problem hiding this comment.
🚨 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.
ad07b02 to
39654f5
Compare
- 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]>
Co-Authored-By: Claude Fable 5 <[email protected]>
9644f3c to
fd28988
Compare
## 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)
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]>
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]>
## 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]>
Summary
editMessagesexperiment enforced by both the app and serverbb thread edit-messageBehavior
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
forkSessionandupToMessageId. 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
(thread_id, source_seq)and add a generated migration plus exact query-plan coverageValidation
The Pi smoke pass used
openai-codex/gpt-5.6-lunabecause the configured Anthropic route was out of extra usage.Simplification pass
expectedRequestSequenceon POST/edit-messagenow atomically edits the latest eligible message; the read-onlyGET /latest-message-editroute,threads.getLatestMessageEdit, and the CLI's GET-then-POST resolution are removed (the CLI's edit-latest is no longer racy)leaseId: each attempt owns exactly one fork, which removes the cross-attempt lease refcounting, join validation, and staging-id hashing, dropsoperationIdfrom both daemon rewind commands, and replaces the runtime's provider allowlist with thesupportsForkcapabilityparseStoredEventwith type narrowing, reuseshasRootStoredTurnStarted, builds the rewind-prepare command with a destructure-rest spread, and resolves the editable-turn scan in one queryuseDraftAttachmentUploads; one-caller helpers and redundant prop round-trips are inlinedRelated to #1114