Repository navigation
Conversation
aotd1
marked this pull request as ready for review
October 1, 2026 07:06
added 9 commits
October 3, 2026 11:52
Import typed terminal turns and uploaded attachments through canonical projections. Support verified legacy adoption and BB-owned message acknowledgements, durable source lookup, and guarded bind/release with distinct source session and runtime handles. Expose owner-bound SDK/CLI surfaces and provider resolver context; document limits and verify transactional, ownership, resume, reset and rollback behavior.
aotd1
force-pushed
the
external-history-api
branch
from
October 3, 2026 09:13
0a4c15a to
76fcbb3
Compare
aotd1
pushed a commit
that referenced
this pull request
Nov 2, 2026
## Human comments ## What was wrong Several cache owners wrote a server reply or the thread-detail bootstrap straight into the React Query cache with `setQueryData` while a fetch of the same key could still be in flight. React Query writes fetch results without checking whether they're older than what's cached (query-core `query.ts`), so the older fetch landed last and put stale data back. Effects included: an environment or host status that stayed stale after opening a thread, a plugin settings form resetting its draft to the old value, a cancelled plugin install flipping back to running, new plugin update jobs dropping out of the list, an `idle` app update phase switching off the progress poll, and the AI service selection flickering back. These are items #2–get-bb#10 from the direct cache write audit (@thread:thr_fjr5x8dzaz). #1 (thread tabs) is fixed separately in get-bb#6611. ## What changed Two fixes, depending on whether the data has a version field: - **Environment and Host keep the newer copy by `updatedAt`** (#2, #3, get-bb#10). The bootstrap ingest (`thread-detail-cache-owner.ts`), the rename reply (`applyEnvironmentUpdateResult`), and the `useEnvironment`/`useHosts` fetches all compare `updatedAt`. The fetch-side check is what catches a fetch that started before the write and lands after it. To make it testable, those fetches now live in `environmentQueryOptions` and `hostsQueryOptions`. Host `status` comes from live daemon sessions and a disconnect doesn't change `updatedAt`, so on a tie the cached copy wins over the bootstrap. The bootstrap only fills an empty cache or replaces strictly older data. Rename replies and fetch results still win ties. - **`setQueryDataOverInFlightFetch`** (`cache-effect-utils.ts`) for data with no version (get-bb#4–get-bb#9): it writes the value, and if a fetch of the key is in flight it cancels that fetch (the cache keeps the written value) and refetches. With nothing in flight it's a plain write. Used by `applyPluginSettingsView`, `applyPluginInstallJob`, `applyPluginUpdateJob`, `hydrateAppUpdateStatus`, `hydrateSystemVersionCache` and `writeCachedAiServices`, so every caller gets the fix. Where the audit suggested an unconditional cancel-write-invalidate (get-bb#7) or a cancel before the write (get-bb#8, get-bb#9), this helper refetches only when a fetch was actually in flight. That avoids an extra request on every write. Forced version and app-update checks update the server's cache, so the trailing unforced refetch returns the forced result. No wire, CLI or plugin API changes. Not covered here: audit items get-bb#11 (plugin safe mode) and get-bb#12 (prompt history), both low risk. Also not covered: a lint rule restricting direct `setQueryData` calls to the helper, which would stop new call sites from bringing the race back. ## How you verified - New tests use real `QueryClient`/`QueryObserver` instances: start a fetch that resolves late with older data, do the write, let the fetch land, then check that the newer value survives (and, for the helper, that the trailing refetch runs). - `thread-detail-cache-owner.test.ts` (new): late environment and host-list fetches after a bootstrap, an older bootstrap over a newer cache, and the equal-`updatedAt` host status case. - `environment-workspace-cache-owner.test.ts`: a late environment fetch after a rename, and an older rename reply over a newer cache. - `in-flight-fetch-writes.test.ts` (new): one row per cache-owner write for get-bb#4–get-bb#9, plus helper tests for the no-fetch case (no extra request) and a fetch of an unobserved query. - With each source change reverted, every race test failed on the stale data and passed once the fix was restored. - `pnpm exec turbo run typecheck lint test --filter=@bb/app`: passed (647 files, 6515 tests; 0 lint errors, no new warnings). After rebasing onto `0472409243` I re-ran the three changed test files (21 tests passed). 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Plugins could not import external conversations as ordinary BB threads without writing BB's database or dispatching a provider turn. They also lacked an explicit way to resume the original source handle and to prepare an existing local project checkout without starting a model. This PR supplies those server-owned operations. Rebase onto BB 0.45.0 also required reconciling migration IDs and advancing SDK/protocol versions beyond the release instead of overwriting upstream changes.
What changed
Rebased onto the exact stable
desktop-v0.45.0commit129f621771a3e275773992db648316966ac207cf. Forkmainpoints to that release;external-history-apicontains the PR changes. Preserved upstream prompt-history APIs, provider controls, Windows host paths and runtime policies.Added public SDK, plugin-bound SDK and CLI
experimental_importHistory,experimental_findExternalThread,experimental_bindExternalSession, andexperimental_releaseExternalSession. Public HTTP routes use normal admission and project/thread lookup. A plugin cannot inject raw SQL or canonical event envelopes.History import never dispatches a model/provider. Stable source identity, generation, external IDs, original order/time and immutable fingerprints make retries idempotent. Rich finalized turns use a strict semantic whitelist; streaming, arbitrary provider events and behind-cursor edits are rejected. Bounded batches atomically update normal events, search, attention and uploaded attachment ownership; notifications follow commit. Explicit verified legacy adoption and BB-owned reply acknowledgement append no duplicate canonical history.
Binding requires an idle, unarchived thread, the owning plugin, matching source session/generation, an enabled provider and a ready same-project environment. It persists an explicitly chosen original provider handle. Only a later ordinary user send starts/resumes the provider. Release uses settled idle release, retains history and never silently interrupts work. Existing bridge methods, capabilities and grammar remain unchanged; optional
experimental_externalSessioncontext travels through existing provider options.Added
environments.experimental_ensureProjectCheckoutandbb environment ensure-project-checkoutfor an existing active host/local-path source. Source ID/path and updated-at CAS, canonical path admission, ownership and lifecycle checks protect creation/reuse. Read-onlyhost.inspect_workspaceinspects the directory/Git metadata; no runtime, provider, prompt, setup hook, clone or checkout mutation. Replays/concurrent calls share one ready unmanaged environment. Windows drive paths follow the release's path validation and normalization.Runtime SDK marker and package are both 0.6.16 (release: 0.6.15). Host daemon protocol is 228 (release: 227) for workspace inspection. Echo-provider example floor matches. Plugin Guide cards/inventory, audit notes, SDK declarations and CLI/guide examples are included.
Regenerated Drizzle migration 0138_external_history and its snapshot after upstream 0136/0137. It adds only the two external tables/indexes. Exact published SQL hashes identify the previous PR's conflicting-number migrations; a guarded immediate transaction verifies schema/history, supplies missing nullable handles, applies skipped upstream migrations and records the new identity without copying/deleting history. Unknown hashes, drift or failed writes abort. Environment ensure adds no schema.
Reused the upstream Plugin SDK package/runtime version regression instead of maintaining a duplicate domain test and custom Turbo task. Removed unrelated formatting changes from existing provider docs, host policy and SDK inventory. Shared the persisted idle/error, active-turn and queue checks across import/bind/release; archive/adoption rules, pending-interaction policy, in-flight guards and both provider-handle ownership checks retain their existing behavior. Eight additional behavioral cases cover passive and bound threads plus interaction policy.
How you verified
All checks below ran in the source checkout on Node 22.19.0 with isolated storage. No installed app, running database, live provider or HomeLab service was changed during this rebase or subsequent cleanup.
pnpm exec turbo run typecheck build --filter=@bb/server --filter=@bb/host-daemon --filter=@bb/cli --filter=@bb/db --filter=@get-bb/plugin-sdk --filter=@bb/sdk --filter=@bb/app --filter=bb-plugin-plugin-api-docs --filter=bb-plugin-echo-provider --output-logs=errors-only: 20 tasks passed, including runtime/declaration builds.Full
@bb/dbsuite: 575 tests / 49 files passed. Final focused external-history upgrade rerun: 8 tests passed, including two additional hash-conflict cases, old passive/interactive migrations, preserved dedupe/session handles, already-applied upstream migrations, restart/retry, schema drift and transaction rollback after an injected ledger failure.Server focused history/session/checkout/version/runtime-config/plugin-SDK suites: 89 tests / 6 files passed. Covers import replay/order/time, search/realtime/attention, no runtime dispatch, invalid batches, ownership, active/queued turns, source CAS, idempotent/concurrent checkout ensure, aliases/lifecycle claims and Windows drive paths. SDK HTTP fixtures now use localhost under upstream DNS rebinding protection.
Host workspace inspection: 3 tests passed. Host daemon contract suites: 70 tests passed. CLI import/bind/release/environment output: 40 tests passed.
SDK public types: 8 tests passed; Plugin SDK public types/fake host: 105 tests passed; provider declarations/version: 29 tests passed; external user timeline projection: 14 tests passed; Plugin Guide surfaces: 11 tests passed.
Published provider-bridge conformance kit: Echo bridge canonical suite passed. No bridge contract extension was introduced by the rebase.
Exact vanilla 0.45.0 source at
129f62177in an isolated detached worktree: vanilla (138 migrations) → this PR (139) → vanilla migration/restart and ordinary thread write → this PR again. Six canonical events, one binding and two dedupe entries stayed unchanged; the repeated import skipped both IDs. Vanilla does not expose the new APIs; this is schema/ordinary-write evidence, not live plugin or Gateway E2E.Focused formatting and
git diff --checkpassed. Original PR head0a4c15ae2is preserved locally asbackup/external-history-before-0.45; GitHub history update uses an explicit SHA lease.Follow-up cleanup at
f5fb8ae40: server history/session/context-guard/context-clear suites 36 tests / 4 files passed; the upstream@get-bb/plugin-sdkpackage/runtime version test 1 test passed. Server + Plugin SDK typecheck/build 9 Turbo tasks passed. Focused TypeScript formatting andgit diff --checkpassed. The additional cases reject active status, unfinished canonical turns and queued work in both passive and bound threads without mutation or runtime dispatch, and preserve distinct interaction policy.Installation and Gateway evidence from the earlier 0.44-based builds remains historical; the rebased build installation has separate evidence below. OpenClaw/Codex plugin development and live sends remain separate work.
/Applications/bb.appand running server/desktop report 0.45.0, exact headf5fb8ae40; installed metadata/server hashes and actual compiled SDK marker 0.6.16 match the signed staged build; host connected. All five experimental HTTP routes reject empty input with 400 and corresponding CLI commands are present. Desktop packaging: 55 Turbo tasks passed, ad hoc signature verification passed. Standard smoke exceeded 20s startup timeout; the same harness with only startup timeout extended to 120s passed, including preload and offline packaged npm checks.bb >=0.44 <0.45manifest upper bound; changed its package/lock to>=0.44 <0.46, retained SDK floor>=0.6.11 <0.7, and verified typecheck, 46 tests, build and reload. Plugin compatibility fix is local commit4a47000on its existing development branch, no release/tag/push.complete/recoveredInPlace, with failed status/logs retained. No additional restart or old DB restoration was needed. This confirms installation/API admission/plugin startup; Gateway interactive E2E remains untested.