Skip to content

Commit 695bbf6

Browse files
anandgupta42claude
andcommitted
fix: Altimate Base fallback ordering and retry latch
Three Codex review findings on the Altimate Base default-no-consent branch: - `fallbackModel()`'s implicit last-resort pick in `local.tsx` used a naive array-order `.find()` instead of mirroring `Provider.defaultModel()`'s ordering, so keyless public Zen could be picked over a registered Base, and Base could beat a provider the user actually connected depending on array position. Extracted `pickImplicitFallbackProvider()` as a pure, directly testable function that mirrors the server's ordering exactly, and added 3 unit tests covering: Base outranking Zen, a credentialed provider outranking Base, and unchanged behavior when Base isn't registered. - `dialog-provider.tsx` and `dialog-model.tsx` set the Altimate Base row's one-shot activation latch before the async `selectAltimateBase()` resolved, and never reset it on failure, permanently bricking the row for the rest of the dialog session after a single failed attempt. Reset the latch when `selectAltimateBase()` returns `false`, and added a full-render retry test confirming a failed selection can be retried and re-fires registration. - `altimate-onboarding.tsx`'s `chooseAltimateBase()` had the same bug, but on the first-run welcome picker: it returned `true` synchronously right after firing the unawaited `selectAltimateBase()` call, so `activateRow()` claimed its one-shot latch before the registration attempt was known to have failed. A failed Base registration then bricked Enter, `/` and mouse-up for the rest of the dialog session on the picker shown to users with no model at all. Reset the latch on failure the same way, keeping the double-input guard intact for the in-flight window, and added a retry test to `dialog-model-welcome.test.tsx` confirming the same row can be retried. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 2d58fb9 commit 695bbf6

7 files changed

Lines changed: 364 additions & 13 deletions

File tree

‎packages/tui/src/component/altimate-onboarding.tsx‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,13 @@ export function DialogModelWelcome(props: {
206206

207207
function chooseAltimateBase(): boolean {
208208
if (!providers().some((provider) => provider.value === "altimate-free")) return false
209-
void selectAltimateBase({ sdk, sync, local, toast, dialog })
209+
// altimate_change — a failed selection must not permanently latch the row inert; only a
210+
// SUCCESSFUL selection is meant to be one-shot (it closes the dialog). Returning `true`
211+
// synchronously below keeps `activateRow`'s double-input guard active for the in-flight
212+
// window; this resets it if the attempt turns out to have failed.
213+
selectAltimateBase({ sdk, sync, local, toast, dialog }).then((selected) => {
214+
if (!selected) activated = false
215+
})
210216
return true
211217
}
212218

‎packages/tui/src/component/dialog-model.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,11 @@ export function DialogModel(props: {
197197
via_search: props.viaSearch ?? false,
198198
})
199199
}
200-
void selectAltimateBase({ sdk, sync, local, toast, dialog }) // altimate_change — no dialog: register then select
200+
// altimate_change — a failed selection must not permanently latch the row inert;
201+
// only a SUCCESSFUL selection is meant to be one-shot (it closes the dialog).
202+
selectAltimateBase({ sdk, sync, local, toast, dialog }).then((selected) => {
203+
if (!selected) activated = false
204+
})
201205
return undefined
202206
},
203207
}

‎packages/tui/src/component/dialog-provider.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,11 @@ export function createDialogProviderOptions() {
201201
via_search: false,
202202
})
203203
}
204-
void selectAltimateBase({ sdk, sync, local, toast, dialog })
204+
// altimate_change — a failed selection must not permanently latch the row inert;
205+
// only a SUCCESSFUL selection is meant to be one-shot (it closes the dialog).
206+
selectAltimateBase({ sdk, sync, local, toast, dialog }).then((selected) => {
207+
if (!selected) altimateBaseActivated = false
208+
})
205209
return
206210
}
207211
// altimate_change end

‎packages/tui/src/context/local.tsx‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,30 @@ export function isPublicZenProvider(provider: {
129129
}): boolean {
130130
return provider.id === "opencode" && provider.options?.["apiKey"] === "public" && !provider.key
131131
}
132+
133+
/**
134+
* `fallbackModel()`'s IMPLICIT last-resort pick (no persisted history behind it): the first
135+
* allowed candidate that is neither Base nor keyless public Zen with Base available, else Base if
136+
* it's available, else whatever the ordinary scan would have picked (e.g. public Zen, when Base
137+
* isn't registered). Mirrors `Provider.defaultModel()`'s ordering exactly.
138+
*
139+
* A single `.find()` over the provider list in array order used to let Base beat a provider the
140+
* user actually connected whenever Base happened to sort first, and let a keyless public-Zen
141+
* candidate be picked outright (not skipped) even with Base available — both were array-position
142+
* accidents, not a ranking. Extracted as a pure function (rather than inlined in the reactive
143+
* memo) so the ordering itself is directly testable without mounting the whole Local context.
144+
*/
145+
export function pickImplicitFallbackProvider<
146+
T extends { id: string; options?: Record<string, unknown>; key?: string },
147+
>(providers: readonly T[], providerAllowed: (id: string) => boolean, baseAvailable: boolean): T | undefined {
148+
const candidates = providers.filter(
149+
(candidate) => candidate.id !== ALTIMATE_BASE_MODEL.providerID && providerAllowed(candidate.id),
150+
)
151+
return (
152+
candidates.find((candidate) => !(baseAvailable && isPublicZenProvider(candidate))) ??
153+
(baseAvailable ? providers.find((candidate) => candidate.id === ALTIMATE_BASE_MODEL.providerID) : undefined)
154+
)
155+
}
132156
// altimate_change end
133157

134158
export function shouldOfferManagedBaseDefault(
@@ -633,12 +657,11 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
633657
// Unlike `recent`, this is an IMPLICIT last-resort pick with no history behind it, so it
634658
// must honor the full allowlist — not just exclude Altimate Base — or it can land on a
635659
// connected provider the project never named either. Base itself is exempt from that
636-
// allowlist check (see the comment above `baseAvailable`).
660+
// allowlist check (see the comment above `baseAvailable`). Ordering is
661+
// `pickImplicitFallbackProvider`'s job — see its declaration above for why.
637662
const configuredProviderIDs = Object.keys(sync.data.config.provider ?? {})
638663
const providerAllowed = (id: string) => configuredProviderIDs.length === 0 || configuredProviderIDs.includes(id)
639-
const provider = sync.data.provider.find(
640-
(candidate) => candidate.id === ALTIMATE_BASE_MODEL.providerID || providerAllowed(candidate.id),
641-
)
664+
const provider = pickImplicitFallbackProvider(sync.data.provider, providerAllowed, baseAvailable)
642665
// altimate_change end
643666
if (!provider) return undefined
644667
const defaultModel = sync.data.provider_default[provider.id]

‎packages/tui/test/cli/tui/dialog-model-welcome.test.tsx‎

Lines changed: 91 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,10 @@
1313
import { createDefaultOpenTuiKeymap } from "@opentui/keymap/opentui"
1414
import { testRender, useRenderer } from "@opentui/solid"
1515
import { expect, test } from "bun:test"
16-
import { onCleanup } from "solid-js"
16+
import { mkdir } from "node:fs/promises"
17+
import path from "node:path"
18+
import { createEffect, onCleanup } from "solid-js"
19+
import { tmpdir } from "../../fixture/fixture"
1720
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
1821
import { TestTuiContexts } from "../../fixture/tui-environment"
1922
import { createEventSource, createFetch, directory } from "../../fixture/tui-sdk"
@@ -35,7 +38,9 @@ const ALL_PROVIDER_IDS = ["altimate-backend", "anthropic", "openai", "google", "
3538
async function mountPicker(
3639
trigger?: PickerTrigger,
3740
availableProviders: string[] = ALL_PROVIDER_IDS,
38-
{ firstRun = true }: { firstRun?: boolean } = {},
41+
// altimate_change — `registerOutcomes` scripts the Altimate Base register endpoint (consumed
42+
// one outcome per call, "ok" once exhausted) so the retry test below can force a failure.
43+
{ firstRun = true, registerOutcomes = [] as Array<"ok" | "error"> }: { firstRun?: boolean; registerOutcomes?: Array<"ok" | "error"> } = {},
3944
) {
4045
const [
4146
{ DialogProvider },
@@ -45,7 +50,7 @@ async function mountPicker(
4550
{ KVProvider },
4651
{ ThemeProvider },
4752
{ TuiConfigProvider },
48-
{ ToastProvider },
53+
{ ToastProvider, useToast },
4954
{ SDKProvider },
5055
{ ProjectProvider },
5156
{ SyncProvider },
@@ -78,7 +83,25 @@ async function mountPicker(
7883
onboarding.resetSetupComplete()
7984
if (firstRun) onboarding.markFirstRunActive()
8085

86+
// altimate_change — repo rule: tests must not touch real global state. Without this, every
87+
// test in this file shared the SAME default `/tmp/opencode/state` (TestTuiContexts's hardcoded
88+
// fallback) for both `kv.tsx`'s `kv.json` file (`paths.state`) and the `Flock.withLock` it takes
89+
// while reading/writing that file (keyed off `Global.Path.state`, overridden separately via
90+
// `OPENCODE_TEST_STATE_HOME` — see context/cycle-stability.test.tsx's comment on the same
91+
// isolation) — resource contention across concurrently-running test files/suites.
92+
const tmp = await tmpdir()
93+
const state = path.join(tmp.path, "state")
94+
await mkdir(state, { recursive: true })
95+
const originalStateHome = process.env.OPENCODE_TEST_STATE_HOME
96+
process.env.OPENCODE_TEST_STATE_HOME = tmp.path
97+
8198
const events: OnboardingTelemetryEvent[] = []
99+
// altimate_change — see `registerOutcomes` above
100+
let registerCallCount = 0
101+
const outcomes = [...registerOutcomes]
102+
// altimate_change — the retry test below polls this instead of a fixed sleep to know when the
103+
// failed selection's promise chain (register -> toast) has actually settled.
104+
const toastMessages: string[] = []
82105
const calls = createFetch((url) => {
83106
if (url.pathname === "/provider") {
84107
return Response.json({
@@ -87,10 +110,27 @@ async function mountPicker(
87110
connected: [],
88111
})
89112
}
113+
if (url.pathname === "/altimate/base/register") {
114+
registerCallCount++
115+
const outcome = outcomes.shift() ?? "ok"
116+
return Response.json(
117+
outcome === "ok" ? { ok: true } : { ok: false, result: "network", message: "offline" },
118+
)
119+
}
90120
return undefined
91121
})
92122
const source = createEventSource()
93123

124+
// altimate_change — see `toastMessages` above
125+
function ToastProbe() {
126+
const toast = useToast()
127+
createEffect(() => {
128+
const message = toast.currentToast?.message
129+
if (message) toastMessages.push(message)
130+
})
131+
return null
132+
}
133+
94134
function Harness() {
95135
const renderer = useRenderer()
96136
const keymap = createDefaultOpenTuiKeymap(renderer)
@@ -99,13 +139,14 @@ async function mountPicker(
99139
onCleanup(off)
100140

101141
return (
102-
<TestTuiContexts>
142+
<TestTuiContexts paths={{ home: tmp.path, state, worktree: tmp.path }}>
103143
<ExitProvider exit={() => {}}>
104144
<OpencodeKeymapProvider keymap={keymap}>
105145
<TuiConfigProvider config={resolvedConfig}>
106146
<ArgsProvider>
107147
<KVProvider>
108148
<ToastProvider>
149+
<ToastProbe />
109150
<RouteProvider>
110151
<SDKProvider url="http://test" directory={directory} fetch={calls.fetch} events={source.source}>
111152
<ProjectProvider>
@@ -141,8 +182,20 @@ async function mountPicker(
141182
return {
142183
app,
143184
events,
185+
// altimate_change — see `registerOutcomes` above
186+
get registerCallCount() {
187+
return registerCallCount
188+
},
189+
// altimate_change — see `toastMessages` above
190+
get toastShown() {
191+
return toastMessages.length > 0
192+
},
144193
async cleanup() {
145194
app.renderer.destroy()
195+
// altimate_change — see the state-isolation comment above
196+
if (originalStateHome === undefined) delete process.env.OPENCODE_TEST_STATE_HOME
197+
else process.env.OPENCODE_TEST_STATE_HOME = originalStateHome
198+
await tmp[Symbol.asyncDispose]()
146199
},
147200
}
148201
}
@@ -229,6 +282,40 @@ test("outside a first run the picker records an impression but not a choice", as
229282
}
230283
})
231284

285+
// altimate_change start — Codex review finding: `chooseAltimateBase()` returned `true`
286+
// synchronously right after firing the (unawaited) `selectAltimateBase()` call, so `activateRow()`
287+
// claimed the one-shot latch before the registration attempt was known to have failed. On the
288+
// first-run welcome picker — the one shown to users with no model at all — a failed Base
289+
// registration then bricked Enter, `/` and mouse-up for the rest of the dialog session. Confirms
290+
// the fix: the same row can be retried after a failure, and the register attempt actually re-fires.
291+
test("a failed Altimate Base selection on the welcome picker can be retried", async () => {
292+
const picker = await mountPicker("first_run", [...ALL_PROVIDER_IDS, "altimate-free"], {
293+
registerOutcomes: ["error", "ok"],
294+
})
295+
try {
296+
// Rows: gateway, anthropic, openai, google, Altimate Base, search — four Down presses lands on
297+
// the Base row.
298+
for (let i = 0; i < 4; i++) picker.app.mockInput.pressKey("ARROW_DOWN")
299+
picker.app.mockInput.pressEnter()
300+
await wait(() => picker.registerCallCount === 1)
301+
// `chooseAltimateBase()` fires `selectAltimateBase()` without awaiting it, so the latch reset
302+
// (on the failure branch) lands a beat after the register call itself resolves. Poll for the
303+
// failure toast — the last thing `selectAltimateBase()` does before returning `false` — rather
304+
// than a fixed sleep, so this doesn't race under load.
305+
await wait(() => picker.toastShown)
306+
307+
// Before the fix, the row's one-shot latch stayed set after the failed attempt above, so this
308+
// second Enter would silently no-op — registerCallCount would stay at 1 forever.
309+
picker.app.mockInput.pressEnter()
310+
await wait(() => picker.registerCallCount === 2)
311+
312+
expect(picker.registerCallCount).toBe(2)
313+
} finally {
314+
await picker.cleanup()
315+
}
316+
})
317+
// altimate_change end
318+
232319
test("a row for a provider the server filtered out does not brick the dialog", async () => {
233320
// The server filters providers via enabled_providers/disabled_providers while this picker renders
234321
// five hardcoded rows. Selecting a filtered-out row used to claim the double-submit latch before

0 commit comments

Comments
 (0)