Skip to content

Import external history and bind original provider sessions - #1

Open
aotd1 wants to merge 11 commits into
mainfrom
external-history-api
Open

aotd1 wants to merge 11 commits into
mainfrom
external-history-api

Conversation

@aotd1

@aotd1 aotd1 commented Oct 1, 2026 •

Copy link
Copy Markdown
Owner

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.0 commit 129f621771a3e275773992db648316966ac207cf. Fork main points to that release; external-history-api contains 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, and experimental_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_externalSession context travels through existing provider options.

  • Added environments.experimental_ensureProjectCheckout and bb environment ensure-project-checkout for 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-only host.inspect_workspace inspects 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/db suite: 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 129f62177 in 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 --check passed. Original PR head 0a4c15ae2 is preserved locally as backup/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-sdk package/runtime version test 1 test passed. Server + Plugin SDK typecheck/build 9 Turbo tasks passed. Focused TypeScript formatting and git diff --check passed. 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.

  • Main desktop installation independently verified 2026-10-03 13:22 (+03): /Applications/bb.app and running server/desktop report 0.45.0, exact head f5fb8ae40; 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.
  • Main data verification: integrity ok, all 465 pre-existing thread IDs retained (466 current at verification), 141 ledger entries including retained old published custom identities, both external tables present. 101,994 pre-install event rows byte-identical; the only 37 absent rows were old rate-limit/context-usage snapshots covered by normal core retention; no conversation event loss. Actual copied-store migration/replay/vanilla-0.45 migration/replay preserved 465 IDs, 101,760 full event rows, 15 bindings and 113 dedupe rows by hashes before runtime resumes. Owner-only stopped-data backup and previous application retained. No DB restore, live test import or external provider send performed.
  • Codex Migrate and Dooffin are running, statusDetail null, both UI bundles SDK 0.6.16 / compatible; Dooffin provider enabled/available. The installation detected Codex Migrate's bb >=0.44 <0.45 manifest 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 commit 4a47000 on its existing development branch, no release/tag/push.
  • Installation recovery evidence: first attempt ran out of disk before app replacement. Temporary backup snapshots now use APFS clones plus the SQLite backup API with free-space admission; closed/WAL fixtures preserve source hashes and owner-only backup permissions. Second attempt installed the new app, then plugin compatibility verification attempted recovery; graceful shutdown timed out, leaving the new app healthy. After the manifest fix, independent installed-state checks passed in place and final status is 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.

AGENT GENERATED

@aotd1
aotd1 marked this pull request as ready for review October 1, 2026 07:06
@aotd1 aotd1 changed the title Add experimental API for passive external conversation history Import external history and bind original provider sessions Oct 2, 2026
Alexey Ashurok 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
aotd1 force-pushed the external-history-api branch from 0a4c15a to 76fcbb3 Compare October 3, 2026 09:13
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]>
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.

1 participant