Skip to content

Commit 3173e44

Browse files
anandgupta42claude
andauthored
fix: offer Altimate Base to every user on an implicit free Zen default (AltimateAI#1302)
* fix: offer Altimate Base to every user on an implicit free Zen default Closes AltimateAI#1301. The 0.11.0 migration to Altimate Base only fired when `opencode/big-pickle` was in persisted `recent`, which only a picker writes. 1,027 of 1,031 Big Pickle machines were implicit-default users with no `recent`, so on 0.11.x they were silently rerouted to the next public free Zen model (`nemotron-3.5-lightning-free`) and never offered Base. TUI (`packages/tui`) - `usesImplicitFreeDefault()`: eligibility is now "launch default resolves to a free public OpenCode Zen model (Big Pickle included), no explicit selection, no project provider allowlist", judged on `fallbackModel()` so a restored session model is never mistaken for the default. - One startup decision in `app.tsx` replaces the two racing effects: prior decline → skip; registered Base → migrate silently; returning user (prompt history at startup, project sessions, or a recent model) → migration disclosure; a brand-new user keeps the first-run welcome picker. A `dialog.replace()` that loses a race falls through instead of latching. - Escape / Ctrl-C on the migration disclosure now routes through the close guard to the same path as explicit No: the decline is persisted AND the provider picker opens, instead of stranding the user on the retired model. - Migration copy names the actual free model being moved. - Telemetry: `altimate_base_confirm_shown` / `altimate_base_choice` / `altimate_base_register_result` now fire for the migration origin (they were gated on the first-run funnel, so the migration was invisible), with an `origin` field. - `PromptHistory` exposes `loaded()` and a one-time `hadHistoryAtStartup()`. Server (`packages/opencode`) - `Provider.defaultModel()` and the ACP default scan: a registered Altimate Base now outranks the keyless public Zen tier (`options.apiKey === "public"`) and nothing else; a keyed Zen account or any BYOK provider still wins. Headless hosts (`serve` behind the VS Code extension) therefore land on Base once the install is registered. Tests: `test/context/local.test.ts` (free-Zen detection, eligibility, recents rewrite), `test/cli/tui/dialog-altimate-base.test.tsx` (migration telemetry without first-run, Escape → decline + picker, generalized copy), `test/provider/provider.test.ts` and `test/acp/default-model.test.ts` (public tier vs keyed Zen vs registered Base, recents precedence unchanged, Big Pickle never migrated headlessly). Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_012uzYijGHdhxvpUzhgWxayo * fix: wrap two remaining hunks in altimate_change block markers The marker guard in CI (with the upstream remote present) flagged two spans that only had single-line marker comments over multi-line code. Co-Authored-By: Claude Fable 5.1 <[email protected]> * chore: drop the upstream product name from five AltimateAI#1301 comments The branding leak audit in CI flags the upstream product name in a single-line-marked test comment; the other four were inside marker blocks but are reworded too so none can surface later. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: address review feedback on the Altimate Base default migration (AltimateAI#1302) Inline findings from Cursor Bugbot, CodeRabbit, cubic, and two Codex passes. TUI - startup decision waits for kv hydration and treats a refusal in either store (kv key or model.json flag) as a decline - disclosure copy and the Big Pickle predicate use the launch default, never a restored session's model - accept path captures the launch default on mount and passes it to migrateLegacyDefault({ from }); after registration the re-check keeps only the explicit/allowlist guards and requires the fallback to be unchanged or Base, so a registered provider sorting first cannot route to the picker and a paid provider appearing mid-dialog cannot be migrated - cleanup persists a decline only for an observed dismiss; Ctrl-C is an "interrupt" that closes without deciding; programmatic closes emit no cancel telemetry - usability (useReady / prompt gate) judges the current model with the current explicit marker, includes an older picker-written free recent, and recent-model cycling marks the pick explicit - prompt history excludes appends that race the startup read from the returning-user snapshot - persistence: every outstanding model.json write is tracked; tests await the real writes instead of sleeping Server - public Zen tier is demoted only when options.apiKey === "public" and no key is configured; fixtures discriminate the two cases - ACP re-reads model.json (recents + decline) at each default selection - own-property checks on recents so prototype-name ids cannot throw Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: queue prompt-history writes until the startup read settles; complete markers - prompt/history.tsx: appends during the startup read update the in-memory store immediately but defer the file write until the read has captured hadHistoryAtStartup, so a racing append can never flip the returning-user signal either way; the read merges with entries appended this launch instead of overwriting them - wrap four spans that only had single-line markers over multi-line code (the marker guard diffs committed HEAD, so these surfaced only in CI) Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: address remaining bot findings on PR AltimateAI#1302 (prompt-history write race, migration telemetry, model cycling, test state isolation) TUI - prompt/history.tsx: serialize the startup rewrite and every append's write through one FIFO write queue (`queueWrite`), so a racing append can no longer be clobbered by a still in-flight startup flush; also enforce the no-consecutive-duplicate and MAX_HISTORY_ENTRIES cap invariants when merging startup-read history with entries appended during the read - altimate-onboarding.tsx: track an explicit `chosen` flag set only inside `no()`/`yes()`, so the unconditional `onCleanup` fallback no longer records `altimate_base_choice` telemetry for a bare process exit / top-level quit (previously misread as a decline because `lastCloseReason` stayed `undefined`, which the old check treated the same as an actual dismissal) - altimate-onboarding.tsx: snapshot `launchDefaultDisplay` alongside `launchDefault` once, at mount, instead of reading the live `fallbackModel()`-backed memo from JSX, so the migration disclosure cannot rename itself mid-dialog once `yes()`'s registration moves the live default - local.tsx: `fallbackModel()` now honors a valid, still-allowed `explicitDefault` before falling through to `recent`'s order, so `cycle()`'s deliberate-pick marker (which intentionally does not reorder `recent`) is reflected as the actual launch default on the next launch instead of silently reopening the migration dialog - ui/dialog.tsx: fix stale comments that still described Ctrl+C as behaving "same as Escape" after Ctrl+C was split into its own "interrupt" reason that deliberately records no decline Tests - Global.Path.state gets the same OPENCODE_TEST_HOME-style test-isolation override `home` already had (via OPENCODE_TEST_STATE_HOME), plus a shared `withTestStateHome` helper in test/fixture/fixture.ts; applied to every test in service-session.test.ts, default-model.test.ts, and provider.test.ts that previously read/wrote the real model.json directly, which raced other test files and risked clobbering real developer state if a run was killed mid-write Co-Authored-By: Claude Fable 5.1 <[email protected]> Co-Authored-By: Claude <[email protected]> * fix: close the altimate_change marker after append()'s closing brace Co-Authored-By: Claude <[email protected]> * fix: only flip prompt-history loaded() after the startup flush settles (AltimateAI#1302 critical finding) - history.tsx: `setLoaded(true)` used to fire before the startup rewrite was even kicked off, so a racing append could queue behind (or, before the previous commit's serialization, race) a flush that hadn't landed on disk yet. `loaded()` becoming true now guarantees this launch's startup flush, if one was needed, has actually settled — not merely "kicked off, and safe only because nothing else raced it yet." - history-startup-race.test.tsx: new regression test asserts the disk content the INSTANT loaded() flips, with no separate `await flushed()`, unlike the pre-existing tests written before `loaded()` implied this. Comment thread: AltimateAI#1302 (comment) Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: round 6 bot review findings on PR AltimateAI#1302 (history race, cross-surface default divergence, kv-ready gate, stale close reason, onboarding skip) TUI - prompt/history.tsx: the startup flush and append()'s trimmed-rewrite branch now snapshot `store.history` to a string SYNCHRONOUSLY at enqueue time (`serializeHistory`), instead of reading it lazily from inside the queued write closure. Combined with removing the earlier `await` before `setLoaded(true)`, all three steps (snapshot, enqueue, flip loaded()) run with no await between them: an append that already ran is already in the snapshot and writes nothing itself (persisted exactly once, by the flush); an append that runs after sees `loaded() === true` and queues its own write behind the flush (persisted exactly once too). This closes both a dropped-append bug (from awaiting the write before setLoaded) and a duplicate-entry bug (from the lazy read) at once. - context/local.tsx: reverted the `explicitDefault`-before-`recent` precedence in `fallbackModel()` — it made the TUI and headless/ACP resolve different launch defaults from the same `model.json` after a cycle, since the server never reads `explicitDefault`, and let a malformed `explicitDefault` (prototype-name `modelID`) poison the TUI default ahead of `recent`'s own validity checks. `cycle()` now passes `{ explicit: true, recent: true }` so the cycled model moves to the front of `recent` instead — the single source of truth for TUI, `Provider.defaultModel()`, and ACP alike. - context/local.tsx: `hasUsableFreeDefault()` no longer reads the kv migration-decline key before `kv.ready` — an unready kv now reads as undecided (assumed usable) instead of "not declined", so the prompt gate can no longer discard a submitted prompt during kv hydration. - context/local.tsx / app.tsx: extracted `shouldSkipOnboardingAtStartup` — app.tsx's startup effect no longer latches "no onboarding needed" off a same-launch setup (an impatient first-run user picking a free model before the effect settles), which used to skip the `onboardingReady()` branch's funnel telemetry and scan gate entirely for that case. - component/altimate-onboarding.tsx: the close guard no longer records `lastCloseReason` for a dismiss vetoed by `busy()` (registration in flight) — that stale reason could otherwise survive into an abrupt teardown and make `onCleanup`'s fallback persist a decline nobody made. Also corrected two comments that still described Ctrl+C as behaving like Escape/dismiss. Server - acp/service.ts: corrected a stale module comment that contradicted the recents loop it sits above — a persisted Big Pickle recent IS honored (matching `Provider.defaultModel()`), only the implicit scans exclude it. Tests - history-startup-race.test.tsx: two new regression tests — an append landing before loaded() flips, and one landing while the startup flush is still in flight — both assert exactly-once persistence with an explicit no-duplicate-lines check. - local.test.ts: new tests for cycle()-via-recents-order, the kv.ready gate, and the onboarding-skip discriminator. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: keep the app.tsx local.tsx import single-line for the marker guard Co-Authored-By: Claude <[email protected]> * fix: Codex HOLD findings on PR AltimateAI#1302 (kv-ready pending direction, cycle() stability, history race test rigor) 1. kv.ready gate direction (local.tsx, altimate-onboarding.tsx, component/prompt/index.tsx): `hasUsableFreeDefaultGated` previously treated an unready kv as "assume usable" (`true`) — the wrong direction. With delayed kv hydration, `--prompt` or a fast manual submit could pass `useReady()` and submit to the implicit public Zen model before onboarding/migration ever ran. It now reports `"pending"` (genuinely undecided), not a boolean guess either way. Every consumer of `useReady()` except the prompt submit gate collapses `"pending"` to `false` (the same conservative default as before kv.ready-awareness existed). The submit gate gets a new `useReadyPending()` seam: a submit attempted while pending defers (keeps the typed prompt, opens nothing) and is automatically retried via a `createEffect` once kv resolves either way — sent if it turns out usable, discarded (matching the normal picker-reopen path) if not. 2. cycle() traversal stability (local.tsx): passing `{ recent: true }` (round 6, fixing a cross-surface TUI/server default divergence) broke `cycle()`'s own navigation — reordering `recent` on every pick meant the next press read its index off a list that had just reshuffled, bouncing between two models instead of visiting every one. `cycle()` now captures its traversal order once, lazily, into a separate `cycleOrder` snapshot that stays stable across a whole cycling sequence (re-captured only if the current model falls out of it, e.g. an unrelated explicit pick) — while still persisting every pick to the front of `recent` via `selectModel(..., { recent: true })`, so cross-surface consistency is unaffected. 3. History startup-race test rigor (history-startup-race.test.tsx): the two round-6 regression tests polled `loaded()` via `Bun.sleep`, which does not reliably keep the startup write "in flight" — confirmed they passed even against the dropped-append bug they were meant to catch. Replaced with three barrier-controlled tests using `spyOn(persistence, "readText"/"writeText")` against manually-resolved deferred promises: append while the read is pending, append while the rewrite's write is still gated/in-flight (FIFO ordering), and append synchronously in the same reactive tick `loaded()` flips (the precise shape that reproduces the lazy-snapshot duplicate bug). All three were confirmed to fail against the relevant old behavior and pass on HEAD before being kept. New tests: cycle-stability.test.tsx (calls the real cycle() three times, asserts the visited sequence — verified fails against the pre-fix bounce), ready-pending.test.tsx (the defer/retry mechanism, verified against both the "sent early" and "usable" directions). Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: scope the shouldSkipOnboardingAtStartup discriminator to a genuine first-run completion cubic (3986532221) correctly flagged this as a regression introduced by the round-7 shouldSkipOnboardingAtStartup fix, not a pre-existing follow-up: `setupComplete()` is a global flag set by ANY model selection (`markSetupComplete()`, called from `DialogModel` on every pick), not only a first-run/impatient-picker completion. A RETURNING user (e.g. an existing Big Pickle user) who did an ordinary `/model` switch while app.tsx's startup effect was still settling made `setupComplete()` true too, falling through to the `onboardingReady()` branch and firing `onboarding_started`/`onboarding_completed`/`scan_gate_shown` telemetry plus `openScanGate()` for a routine model change — not a genuine first run. Fix: `firstRunOpenedThisLaunch` (altimate-onboarding.tsx) is a new one-way latch, set only when the first-run picker actually opens THIS launch — app.tsx's own startup fallthrough, or the prompt gate's equivalent (component/prompt/index.tsx now calls `markFirstRunActive()` there too, closing the gap cubic named explicitly). app.tsx's `shouldSkipOnboardingAtStartup` call site now passes `setupComplete() && firstRunOpenedThisLaunch()` instead of the bare global flag — true only for a genuine same-launch first-run completion, so a returning user's routine switch reads false and keeps skipping exactly as before this whole discriminator existed. Tests: two new tests in local.test.ts exercise the real production signals (markSetupComplete/markFirstRunActive/firstRunOpenedThisLaunch) against the actual discriminator computation app.tsx performs — a returning user's routine switch must skip (no telemetry, no scan gate), a genuine first-run completion must not skip. Confirmed the second test fails when the `firstRunOpenedThisLaunch` latch is temporarily removed, then passes again restored. Removed the corresponding item from tracking issue AltimateAI#1303 (fixed directly, not deferred). Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: Codex re-review round 8 (cycleOrder staleness, ready-pending test coverage) 1. cycleOrder goes stale after an external recents change (local.tsx): the round-7 fix (cycleOrder, re-captured only when the current model fell out of the snapshot) still went stale the moment a PICKER selection reordered `recent` without also knocking the current model out of the old snapshot. Codex's repro: [A, B, C], cycle once, then pick D and A via the picker -> recents [A, D, C, B]; A stays present in the stale [A, B, C] snapshot the whole time, so the round-7 check never re-fires, and D stays permanently unreachable by cycling. Fixed with a `recentsVersion` counter (bumped by a new `setRecent` wrapper — the only path that writes to `modelStore.recent` now) and a `cycleOrderVersion` on the cycle() closure: cycle() re-captures whenever the live version has moved past what it last saw or resynced to, which happens for ANY external write, picker included — while resyncing after its own write so repeated presses with nothing else interleaved keep reusing the same stable snapshot. Regression test: extended cycle-stability.test.tsx's existing "stable order" scenario with Codex's exact repro (pick D and A via the picker after cycling once, assert D becomes reachable and the re-captured order stays stable afterward). All three tests in that file now share one mount via beforeAll/afterAll rather than each mounting independently — a second or third independent heavy provider-tree mount in this file was found to reproducibly hang during its own bootstrap (a test-infrastructure resource-contention issue, worse the more work a prior mount did, unrelated to anything under test) — chaining the scenarios onto one shared, stateful mount sidesteps it while still exercising the real cycle() end to end. Confirmed the new assertion fails (D never reachable, times out) against the round-7-only invalidation check, and passes on HEAD. 2. ready-pending.test.tsx exercised a hand-rolled reimplementation of the defer/retry shape instead of production code, so reverting the real fix in component/prompt/index.tsx left it passing regardless. Extracted `createDeferredRetry` (packages/tui/src/util/signal.ts) — a small, generic, reactive defer-then-retry primitive — and made both prompt/index.tsx's submit gate and the test's harness call the SAME function. Confirmed the test fails (2 of 3 cases, exactly the ones relying on automatic retry) when `createDeferredRetry`'s retry is temporarily broken, and passes on HEAD once restored. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: wrap createDeferredRetry in altimate_change markers Co-Authored-By: Claude <[email protected]> * fix: latch first-run only after a successful prompt-gate dialog.replace() Bonus fix found by cursor (3986991408) and cubic (3987011218) re-reviewing the setupComplete fix (ce0d3af) moments after it landed: `markFirstRunActive()` in the prompt gate's `!ready()` branch fired unconditionally, before `dialog.replace()` even ran — including when `dialog.replace()` loses a race to another dialog and returns `false` without opening anything. That latched `firstRunOpenedThisLaunch`/`firstRunActive` for a picker nobody ever saw, so a returning user's LATER, unrelated `/model` pick would look like a genuine first-run completion and fire onboarding telemetry + the scan gate — the inverse of the bug ce0d3af was fixing. Mirrors app.tsx's own identical, already-correct pattern for its own first-run fallthrough: check `dialog.replace()`'s return value and only call `markFirstRunActive()` once it actually succeeded. No new test: this is a direct application of an already-established, already-tested pattern (app.tsx's own `shown` check) to a second call site; the fix was verified via typecheck and the full test suite, not a new mount-based test — exercising the full submit path would need mounting the whole `<Prompt>` component (session/workspace/editor/move dependencies), which this session already assessed as disproportionate for a single conditional-latch fix. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: Codex re-review round 9 (onboardingReady() latch, deferred-submit staleness) 1. app.tsx's `onboardingReady()` branch (~783) had the same class of bug as the `shouldSkipOnboardingAtStartup` branch above it (cubic 3986532221), just reached from a different starting condition: a bare `setupComplete()` check. `onboardingReady()` (`useReady()`) is also true via `connected()`, not only via `hasUsableFreeDefault()` — so a returning user with a configured legacy default (e.g. Big Pickle) who switches `/model` to a PAID model has BOTH of `shouldSkipOnboardingAtStartup`'s skip predicates false (a paid pick isn't covered by either `hasExistingLegacySelection()` or `hasUsableFreeDefault()`), falls through to this branch, and `onboardingReady()` is already true via `connected()`. If that `/model` switch raced app.tsx's startup effect, `setupComplete()` alone read as true even though no first-run picker ever opened, firing onboarding telemetry and the scan gate for an ordinary provider switch. Fixed the same way as the branch above: require `firstRunOpenedThisLaunch()` alongside `setupComplete()`. Tests: two new cases in local.test.ts against the real production signals — both skip predicates false and the latch false fires nothing; the latch true still fires. 2. A deferred submission could include later, unrelated edits: defer prompt A (kv/readiness still pending), edit the box to B without pressing Enter again, readiness resolves — B was silently auto-submitted, a send the user never asked for. `createDeferredRetry` (util/signal.ts) now takes an optional `getRevision` that is snapshotted at `.defer()` time and compared against the live value right before the retry would fire; a mismatch cancels the retry entirely instead of firing against stale state. component/prompt/index.tsx's submit gate passes `unwrap(store.prompt)` (text + attachments) as the revision. Test: ready-pending.test.tsx's harness passes `getRevision` through the same shared primitive; new cases assert an edited-while-deferred submission is silently canceled (not auto-sent), and an unedited one still sends normally. Confirmed the edited case fails (B gets auto-sent) when the revision check is temporarily removed from `createDeferredRetry`, and passes restored. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: don't discard the typed prompt when the prompt-gate picker fails to open Real data-loss bug caught by cursor (3987148590) and cubic (3987174889) moments after the previous fix landed: when `dialog.replace()` loses a race to another dialog (e.g. a close-guarded one — a deferred submit's automatic retry can hit this path directly, bypassing the focus check a manual Enter press would go through) and returns `false`, the previous fix correctly skipped `markFirstRunActive()` but still fell through to clear the input, extmarks, and prompt store — silently discarding whatever the user just typed even though no picker ever opened to explain why. Mirrors app.tsx's own identical `shown` check fully now: return immediately on `!shown`, before touching anything, same as app.tsx's own `if (!shown) return`. The user can just submit again once whatever is blocking the dialog clears. No new test: exercising this exact race (a close-guarded dialog specifically vetoing `dialog.replace()`) would need mounting the full `<Prompt>` component with a real `DialogProvider` and a second, close-guarded dialog already open — the same mount-cost tradeoff already assessed and declined for the sibling fixes in this same function. Verified via typecheck and the full test suite. Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: fold cycle-stability tests into one, isolate state dir from real Flock lock artifacts This repo's rule is no order-dependent or resource-contention-prone tests; both cubic findings on cycle-stability.test.tsx are in scope: 1. The three sequential `test.serial` blocks sharing one `beforeAll`/`afterAll` mount made the third test depend on mutations the first two produced — running it alone (a `-t` filter or `--only-failures`) failed. Folded into ONE `test()` over a single local mount, with five labelled phases (a small `phase()` helper wraps each block so an assertion failure's message names exactly which stage failed) covering the same ground as before: stable traversal order, persisting picks to the front of `recent`, picker-driven staleness/re-discovery, and stable re-traversal afterward. 2. `kv.tsx`'s `Flock.withLock` lock directory is derived from `Global.Path.state` (packages/core/src/global.ts), which had no test-isolation override at all — only `Global.Path.home` did. The test's `kv.json` FILE itself was always correctly isolated via `paths.state` (TestTuiContexts), but the LOCK it takes while reading/writing that file was not, so it could still touch the real, current developer's global state directory. Added an `OPENCODE_TEST_STATE_HOME` override to `Global.Path.state` (mirroring `Global.Path.home`'s existing `OPENCODE_TEST_HOME` pattern, already used throughout this codebase's tests), and made `Flock.setGlobal` take a getter over `Path.state` instead of a frozen snapshot — `Flock`'s lock root was captured once at this module's import time, before any test's own setup code could set the env var, so a plain override on `Path.state` alone would not have been enough. The test now sets/restores this env var around its mount. Verified empirically: before this fix, this test's own runs left new (and orphaned, if killed mid-run) `.lock` directories in the real `~/.local/state/altimate-code/locks` — confirmed via the directory's own mtime changing across a run with the fix temporarily reverted, and staying untouched with it applied. Also confirmed via typecheck (packages/core, packages/tui, packages/opencode) that the getter-based `Flock.setGlobal` argument still satisfies `FlockGlobal`'s type. Removed both items from tracking issue AltimateAI#1303 (fixed directly, not deferred). Co-Authored-By: Claude Fable 5.1 <[email protected]> * fix: snapshot the deferred-submit revision serialized; share the onboardingReady() predicate; re-defer test; orphan marker - util/signal.ts: `createDeferredRetry` captured `getRevision()` by reference. Solid's `unwrap` returns the store's raw underlying object, the same one later edits mutate in place, so the defer-time value and the retry-time value were one object and an edited prompt was still auto-sent. The defer-time revision is now stored serialized and the live value is serialized again before retrying (cursor 3987286236, cubic 3987320771). ready-pending.test.tsx's harness now hands the primitive one live mutable object, the production shape; its edited-while-deferred test fails on the old primitive. - ready-pending.test.tsx: the "re-deferred" test now actually re-defers (Enter twice while pending) and asserts exactly one send (kilo 3987319604). - context/local.tsx + app.tsx: the onboardingReady() branch's discriminator is an exported `shouldFireFirstRunFunnelAtStartup` that app.tsx calls and local.test.ts tests, instead of an expression the tests re-derived. - app.tsx: remove an orphan `// altimate_change end`. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
1 parent 463b89c commit 3173e44

27 files changed

Lines changed: 3511 additions & 327 deletions

‎docs/docs/configure/providers.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ registration request; **No** is selected by default. After registration, the mod
6868
explicit model is selected. Big Pickle is retired as a new selection — it no longer appears in the
6969
picker or the full model catalog for users choosing a model for the first time. Users already on
7070
Big Pickle are still detected on launch and offered Altimate Base through the same consent gate.
71+
If you decline the default switch, `declinedManagedBaseDefault: true` in the state directory's `model.json` keeps public Zen ahead of registered Base for headless and ACP defaults, with Base used only as a last resort; accepting migration or explicitly selecting Base clears the flag.
7172

7273
Official release binaries embed the current gateway endpoint at build time. Operators and local
7374
development can override it without changing code:

‎docs/docs/reference/telemetry.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,8 @@ We collect the following categories of events:
5757
| `onboarding_started` | The first-run setup gate opened (fresh launch with no usable model). |
5858
| `model_picker_shown` | The provider picker was displayed. `trigger` distinguishes the first run from `/connect`, from declining Altimate Base, and from the prompt gate. |
5959
| `provider_selected` | A provider row was chosen — `altimate_gateway`, `altimate_base`, `anthropic`, `openai`, `google`, `search_all`, or `other` for anything outside the curated five. `provider_id` carries the raw id only for publicly-known providers, so a provider you named yourself in config is reported as `other` with no name attached. `via_search` marks a pick made inside the full catalogue after choosing "Search all providers…". **Choosing search emits this event twice for one user** — once as `search_all`, then again with the provider actually chosen — so count distinct users or filter on `via_search`, not raw event count. Recorded at the moment of choice, so a sign-in that is then cancelled still counts. |
60-
| `altimate_base_confirm_shown` / `altimate_base_choice` | The Altimate Base disclosure was shown (`welcome` or `model` origin), and what the user decided (`accept`/`cancel`). |
61-
| `altimate_base_register_result` | The consented registration outcome: `success`, `rate_limited`, `unavailable`, `network`, or `error`. No credential or gateway response body is included. |
60+
| `altimate_base_confirm_shown` / `altimate_base_choice` | The Altimate Base disclosure was shown, and what the user decided (`accept`/`cancel`). `origin` is `welcome`, `model`, or `migration` (returning free-default users offered Altimate Base on launch); required for the disclosure event and optional for the choice event. |
61+
| `altimate_base_register_result` | The consented registration outcome: `success`, `rate_limited`, `unavailable`, `network`, or `error`. Optional `origin` is `welcome`, `model`, or `migration` (returning free-default users offered Altimate Base on launch). No credential or gateway response body is included. |
6262
| `gateway_device_code_issued` | The Altimate Gateway authorize URL was built and the browser open attempted. **Name note:** the flow is a browser loopback OAuth — there is no device code. The name follows the original event spec. |
6363
| `gateway_auth_completed` / `gateway_auth_failed` | Gateway sign-in outcome. `reason` is `timeout`, `denied`, or `error` — never the underlying message, which can contain the instance name. An unrecognised callback state does not reject the pending attempt, so a CSRF mismatch surfaces as `timeout`. |
6464
| `instance_connected` | Credentials received and saved. `time_to_connect_ms` runs from the start of the authorize call, so it includes the browser launch. No instance or tenant name is sent. |

‎packages/core/src/global.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,34 @@ const paths = {
3030
repos: path.join(data, "repos"),
3131
cache,
3232
config,
33-
state,
33+
// altimate_change start — cubic review (3986917361): unlike `home` above, `state` was a plain
34+
// const with no test-isolation override, so any consumer reading `Global.Path.state` — or
35+
// `Flock`'s lock directory, which is derived from it (see the `Flock.setGlobal` call below) —
36+
// silently touched the REAL, current developer's state directory in tests. Mirror `home`'s
37+
// pattern: a getter honoring `OPENCODE_TEST_STATE_HOME`, read fresh on every access.
38+
get state() {
39+
return process.env.OPENCODE_TEST_STATE_HOME ?? state
40+
},
41+
// altimate_change end
3442
tmp,
3543
}
3644

3745
export const Path = paths
3846

39-
Flock.setGlobal({ state })
47+
// altimate_change start — cubic review (3986917361): `Flock.setGlobal` used to be given the
48+
// frozen `state` const directly, snapshotted once at this module's import time — even after
49+
// adding the `OPENCODE_TEST_STATE_HOME` override to `Path.state` above, `Flock`'s own internal
50+
// lock-directory resolution would still have kept using whatever `state` was BEFORE any test set
51+
// that env var (module imports happen once, before a test's own `beforeAll`/mount code runs). A
52+
// getter-backed property here means `Flock`'s `root()` — which just reads `global.state` as a
53+
// plain property — re-evaluates `Path.state` fresh on every lock acquisition instead, so setting
54+
// `OPENCODE_TEST_STATE_HOME` redirects BOTH `Global.Path.state` reads and `Flock`'s lock root.
55+
Flock.setGlobal({
56+
get state() {
57+
return Path.state
58+
},
59+
})
60+
// altimate_change end
4061

4162
await Promise.all([
4263
fs.mkdir(Path.data, { recursive: true }),

‎packages/opencode/src/acp/directory.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,14 @@ export type Snapshot = {
3434
readonly defaultModeID: string
3535
readonly availableCommands: readonly Command.Info[]
3636
readonly defaultModel?: DefaultModel
37+
// altimate_change start — cache the project config that drives default-model selection, so the
38+
// mutable model.json state (recents, decline flag) can be re-read at each selection instead of
39+
// being frozen into the snapshot
40+
readonly defaultModelConfig?: {
41+
readonly model?: string
42+
readonly provider?: Record<string, unknown>
43+
}
44+
// altimate_change end
3745
}
3846

3947
export interface LoaderInterface {
@@ -61,6 +69,9 @@ export const build = (input: {
6169
readonly defaultModeID: string
6270
readonly commands: readonly Command.Info[]
6371
readonly defaultModel?: DefaultModel
72+
// altimate_change start — see `Snapshot.defaultModelConfig`
73+
readonly defaultModelConfig?: Snapshot["defaultModelConfig"]
74+
// altimate_change end
6475
}): Snapshot => {
6576
const modelOptions = Provider.sort(
6677
Object.values(input.providers).flatMap((provider) =>
@@ -110,6 +121,9 @@ export const build = (input: {
110121
: (input.modes[0]?.id ?? input.defaultModeID),
111122
availableCommands: input.commands,
112123
...(input.defaultModel ? { defaultModel: input.defaultModel } : {}),
124+
// altimate_change start — see `Snapshot.defaultModelConfig`
125+
...(input.defaultModelConfig ? { defaultModelConfig: input.defaultModelConfig } : {}),
126+
// altimate_change end
113127
}
114128
}
115129

‎packages/opencode/src/acp/service.ts‎

Lines changed: 70 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -805,19 +805,6 @@ async function loadDirectorySnapshot(sdk: OpencodeClient, directory: string) {
805805
// provider either, so it fails closed the same way an explicit allowlist without it does.
806806
const snapshotProviders = configLoaded && !hasProviderAllowlist ? providers : withoutManagedBase()
807807
// altimate_change end
808-
const defaultModelStarted = performance.now()
809-
// altimate_change start — resolve the default against the SAME filtered snapshot advertised to
810-
// the client. Resolving against the unfiltered `providers` map let a project that sets
811-
// `model: "altimate-free/altimate-base"` alongside any `provider` allowlist end up with a
812-
// `defaultModel` pointing at a provider this snapshot had just excluded — ACP would still
813-
// select and route the managed model even though it was hidden from `modelOptions`.
814-
const defaultModel = defaultModelFromConfig(
815-
config?.model,
816-
snapshotProviders,
817-
config?.provider as Record<string, unknown> | undefined,
818-
)
819-
// altimate_change end
820-
ACPProfile.duration("acp.directory.defaultModel.resolve", defaultModelStarted, { configured: !!defaultModel })
821808
const modes = agents
822809
.filter((agent) => agent.mode !== "subagent" && agent.hidden !== true)
823810
.map((agent) => ({
@@ -846,7 +833,10 @@ async function loadDirectorySnapshot(sdk: OpencodeClient, directory: string) {
846833
modes,
847834
defaultModeID: agents.find((agent) => agent.mode === "primary" && agent.hidden !== true)?.name ?? "build",
848835
commands: commands.toSorted((a, b) => a.name.localeCompare(b.name)),
849-
...(defaultModel ? { defaultModel } : {}),
836+
// altimate_change start — cache project config, but resolve mutable model.json state at each
837+
// default selection
838+
defaultModelConfig: { model: config?.model, provider: config?.provider },
839+
// altimate_change end
850840
})
851841
})
852842
}
@@ -856,6 +846,10 @@ export function defaultModelFromConfig(
856846
configuredModel: string | undefined,
857847
providers: Record<ProviderV2.ID, Provider.Info>,
858848
providerFilter?: Record<string, unknown>,
849+
// altimate_change start — persisted recents and default-switch consent, normalized by the shared state reader
850+
declinedManagedBaseDefault = false,
851+
recent: Awaited<ReturnType<typeof Provider.readDefaultModelState>>["recent"] = [],
852+
// altimate_change end
859853
): Directory.DefaultModel | undefined {
860854
// altimate_change start — fork Provider ids are branded ProviderID/ModelID; re-brand to core ProviderV2.ID/ModelV2.ID (identity at runtime)
861855
const configured = configuredModel
@@ -869,6 +863,16 @@ export function defaultModelFromConfig(
869863
const configuredProviderEntries = Object.keys(providerFilter ?? {})
870864
const hasProviderAllowlist = configuredProviderEntries.length > 0
871865

866+
for (const entry of recent) {
867+
const providerID = ProviderV2.ID.make(entry.providerID)
868+
const modelID = ModelV2.ID.make(entry.modelID)
869+
if (!Object.hasOwn(providers, providerID)) continue
870+
if (!Object.hasOwn(providers[providerID].models, modelID)) continue
871+
// Match Provider.defaultModel(): only managed Base recents are restricted by an allowlist.
872+
if (entry.providerID === "altimate-free" && hasProviderAllowlist) continue
873+
return { providerID, modelID }
874+
}
875+
872876
// Prefer altimate-backend/altimate-default when the fork's backend is available and the user
873877
// hasn't pinned a model — restores dropped fork behavior (the merge fell straight through to the
874878
// opencode provider, routing ACP clients away from altimate's backend). Honors an explicit
@@ -882,11 +886,22 @@ export function defaultModelFromConfig(
882886
return { providerID: ProviderV2.ID.make("altimate-backend"), modelID: ModelV2.ID.make("altimate-default") }
883887
}
884888

885-
// First-session ACP startup must not scan historical sessions just to infer
886-
// a default. Configured model, opencode provider, then sorted best model keep
887-
// the protocol response deterministic without extra session/message reads.
889+
// First-session ACP startup must not scan historical sessions just to infer a default.
890+
// Recents above come from model.json, not session storage. After configured/recent choices
891+
// and the backend preference, use the opencode provider, then the sorted best model,
892+
// without extra session/message reads.
893+
const baseProvider = providers[ProviderV2.ID.make("altimate-free")]
894+
const registeredBaseAvailable = Boolean(baseProvider?.models[ModelV2.ID.make("altimate-base")]) && !hasProviderAllowlist
888895
const providerAllowed = (id: string) =>
889-
id !== "altimate-free" && (!hasProviderAllowlist || Object.prototype.hasOwnProperty.call(providerFilter, id))
896+
id !== "altimate-free" &&
897+
(!hasProviderAllowlist || Object.prototype.hasOwnProperty.call(providerFilter, id)) &&
898+
!(
899+
registeredBaseAvailable &&
900+
!declinedManagedBaseDefault &&
901+
id === "opencode" &&
902+
providers[ProviderV2.ID.make(id)]?.options.apiKey === "public" &&
903+
!providers[ProviderV2.ID.make(id)]?.key
904+
)
890905
const opencodeProvider = providerAllowed("opencode") ? providers[ProviderV2.ID.make("opencode")] : undefined
891906
const opencodeModel = opencodeProvider
892907
? Provider.sort(Object.values(opencodeProvider.models)).find((model) => model.id !== "big-pickle")
@@ -901,21 +916,41 @@ export function defaultModelFromConfig(
901916
).find((model) => !(model.providerID === "opencode" && model.id === "big-pickle"))
902917
if (best) return { providerID: ProviderV2.ID.make(best.providerID), modelID: ModelV2.ID.make(best.id) }
903918

904-
// Altimate Base replaces Big Pickle as the free fallback, but only as a LAST resort and only
905-
// after the user consented and registered (which is why it is present in `providers`). Anything
906-
// else connected outranks the request-logging tier. A project provider block cannot force the
907-
// managed model; an explicit configured model above remains authoritative.
908-
const baseProvider = providers[ProviderV2.ID.make("altimate-free")]
909-
if (!hasProviderAllowlist && baseProvider?.models[ModelV2.ID.make("altimate-base")]) {
919+
// Altimate Base replaces Big Pickle as the free fallback only after the user consented and
920+
// registered (which is why it is present in `providers`). Anything the user actually connected
921+
// outranks the request-logging tier, except the keyless public Zen tier, which ranks below
922+
// registered Base unless the user declined the default switch in model.json. After a decline,
923+
// public Zen stays in both scans and Base is only the last resort. A keyed Zen account still
924+
// wins. A project provider block cannot force the managed model; an explicit configured model
925+
// above remains authoritative.
926+
if (registeredBaseAvailable) {
910927
return { providerID: ProviderV2.ID.make("altimate-free"), modelID: ModelV2.ID.make("altimate-base") }
911928
}
912929
return undefined
913930
// altimate_change end
914931
}
915932

916-
// altimate_change start — keep Big Pickle explicitly selectable but never choose it implicitly
917-
export function selectDefaultModel(snapshot: Directory.Snapshot) {
918-
if (snapshot.defaultModel) return snapshot.defaultModel
933+
// altimate_change start — Big Pickle is never chosen by the implicit provider/model SCANS below
934+
// (the `opencodeModel`/`best` fallbacks both exclude it) — but a persisted `recent` entry is the
935+
// user's own past pick, so it is honored verbatim, including a legacy Big Pickle one (kilo review
936+
// round 6, 3986171219: mirrors `Provider.defaultModel()`'s identical recents-loop rationale in
937+
// provider.ts — the TUI owns the migration because it owns the disclosure, so rewriting it here
938+
// would move a declining user to the request-logging tier with no prompt).
939+
export async function selectDefaultModel(snapshot: Directory.Snapshot) {
940+
if (snapshot.defaultModelConfig) {
941+
const started = performance.now()
942+
const { recent, declinedManagedBaseDefault } = await Provider.readDefaultModelState()
943+
// Resolve against the filtered catalogue so an excluded managed provider cannot be selected.
944+
const selected = defaultModelFromConfig(
945+
snapshot.defaultModelConfig.model,
946+
snapshot.providers,
947+
snapshot.defaultModelConfig.provider,
948+
declinedManagedBaseDefault,
949+
recent,
950+
)
951+
ACPProfile.duration("acp.directory.defaultModel.resolve", started, { configured: !!selected })
952+
if (selected) return selected
953+
} else if (snapshot.defaultModel) return snapshot.defaultModel
919954
// Big Pickle remains explicitly selectable for existing users, but Altimate Base replaces it as
920955
// the free implicit choice. Do not silently route a new ACP session back to Big Pickle when it is
921956
// the first (or only) sorted catalogue entry and no usable default was resolved above.
@@ -935,17 +970,14 @@ function availableModel(snapshot: Directory.Snapshot, model: Directory.DefaultMo
935970
: undefined
936971
}
937972

938-
function requireDefaultModel(snapshot: Directory.Snapshot) {
939-
const selected = selectDefaultModel(snapshot)
940-
return selected
941-
? Effect.succeed(selected)
942-
: Effect.fail(
943-
new ACPError.ServiceFailureError({
944-
safeMessage: "No supported model is configured. Register Altimate Base or configure another provider.",
945-
service: "model",
946-
}),
947-
)
948-
}
973+
const requireDefaultModel = Effect.fn("ACP.requireDefaultModel")(function* (snapshot: Directory.Snapshot) {
974+
const selected = yield* request(() => selectDefaultModel(snapshot), "model")
975+
if (selected) return selected
976+
return yield* new ACPError.ServiceFailureError({
977+
safeMessage: "No supported model is configured. Register Altimate Base or configure another provider.",
978+
service: "model",
979+
})
980+
})
949981
// altimate_change end
950982

951983
function detectSlashCommand(parts: ReturnType<typeof promptContentToParts>) {

‎packages/opencode/src/altimate/telemetry/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1027,18 +1027,20 @@ export namespace Telemetry {
10271027
type: "altimate_base_confirm_shown"
10281028
timestamp: number
10291029
session_id: string
1030-
origin: "welcome" | "model"
1030+
origin: "welcome" | "model" | "migration"
10311031
}
10321032
| {
10331033
type: "altimate_base_choice"
10341034
timestamp: number
10351035
session_id: string
1036+
origin?: "welcome" | "model" | "migration"
10361037
choice: "accept" | "cancel"
10371038
}
10381039
| {
10391040
type: "altimate_base_register_result"
10401041
timestamp: number
10411042
session_id: string
1043+
origin?: "welcome" | "model" | "migration"
10421044
result: "success" | "rate_limited" | "unavailable" | "network" | "error"
10431045
}
10441046
| {

‎packages/opencode/src/global/index.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,19 @@ export namespace Global {
2424
log: path.join(data, "log"),
2525
cache,
2626
config,
27-
state,
27+
// altimate_change start — cubic review round 5, P2: unlike `home` above, `state` was a
28+
// plain module-load-time const with no test-isolation override, so any test reading or
29+
// writing through `Global.Path.state` (recent-model / migration-decline persistence in
30+
// `model.json`) was silently touching the REAL, current developer's state directory —
31+
// racing any other test file doing the same thing in parallel, and risking clobbering real
32+
// state if a test run were killed mid-write. Mirror `home`'s pattern with its own getter and
33+
// env var so `Global.Path.state` can be redirected to a throwaway temp dir per test (see
34+
// `test/fixture/fixture.ts`'s `withTestStateHome`), without changing production behavior —
35+
// the getter is evaluated fresh on every access, and the env var is unset outside tests.
36+
get state() {
37+
return process.env.OPENCODE_TEST_STATE_HOME || state
38+
},
39+
// altimate_change end
2840
}
2941
}
3042

0 commit comments

Comments
 (0)