Skip to content

Commit b01a139

Browse files
anandgupta42claude
andcommitted
fix: Codex HOLD findings on PR #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]>
1 parent 96375f6 commit b01a139

8 files changed

Lines changed: 708 additions & 121 deletions

File tree

‎packages/tui/src/app.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -745,7 +745,11 @@ function App(props: { onSnapshot?: () => Promise<string[]>; pluginHost: TuiPlugi
745745
if (
746746
shouldSkipOnboardingAtStartup(
747747
local.model.hasExistingLegacySelection(),
748-
local.model.hasUsableFreeDefault(),
748+
// `=== true`: `hasUsableFreeDefault()` can also return `"pending"` (see its declaration
749+
// and `hasUsableFreeDefaultGated` in local.tsx) — but this whole effect already returned
750+
// early above unless `kv.ready`, so it is always a plain boolean by the time it runs
751+
// here; the explicit check just satisfies the union type without widening it elsewhere.
752+
local.model.hasUsableFreeDefault() === true,
749753
setupComplete(),
750754
)
751755
) {

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

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,33 @@ export function useReady() {
7777
// component/prompt/index.tsx). `LocalProvider` wraps the whole app above `DialogProvider` (see
7878
// app.tsx), so `useLocal()` is always available to every caller of `useReady()`.
7979
const local = useLocal()
80-
return createMemo(() => connected() || setupComplete() || local.model.hasUsableFreeDefault())
80+
// altimate_change — Codex HOLD finding 1: `hasUsableFreeDefault()` can now return `"pending"`
81+
// (kv not hydrated yet, see its declaration in local.tsx) as well as a boolean. Every consumer
82+
// of `useReady()` EXCEPT the prompt submit gate only needs a plain boolean (display text,
83+
// whether a command is enabled, the first-run chat lock) — `"pending"` collapses to `false` for
84+
// all of them, the same conservative default this code had before kv.ready-awareness existed.
85+
// `useReadyPending()` below is the ONE seam the submit gate uses to see the pending state
86+
// itself, so it can defer instead of discarding.
87+
return createMemo(() => connected() || setupComplete() || local.model.hasUsableFreeDefault() === true)
8188
// altimate_change end
8289
}
8390

91+
// altimate_change start — Codex HOLD finding 1: true only when overall readiness cannot be
92+
// decided YET — none of `connected()`/`setupComplete()` are already true, and the free-default
93+
// predicate is specifically `"pending"` (kv still hydrating), not a settled `false`. The prompt
94+
// submit gate (component/prompt/index.tsx) is the one caller that needs this: `useReady()` alone
95+
// cannot distinguish "genuinely not usable, show the picker" from "don't know yet, kv is still
96+
// loading" — both read as `false` there by design (see `useReady()`'s comment above), which is
97+
// the right default for every OTHER consumer (display text, command enablement) but wrong for a
98+
// submit gate whose `false` branch discards the typed prompt. This predicate lets the submit
99+
// gate keep the prompt and retry once kv resolves, instead of guessing either way.
100+
export function useReadyPending() {
101+
const connected = useConnected()
102+
const local = useLocal()
103+
return createMemo(() => !connected() && !setupComplete() && local.model.hasUsableFreeDefault() === "pending")
104+
}
105+
// altimate_change end
106+
84107
/**
85108
* Setup completion ONLY — deliberately without the `connected()` term.
86109
*

‎packages/tui/src/component/prompt/index.tsx‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ import { useDialog } from "../../ui/dialog"
4848
import { DialogProvider as DialogProviderConnect, WARNLIST } from "../dialog-provider"
4949
// altimate_change — first-run submit gate: open the curated welcome picker instead
5050
// of erroring when no model is ready yet (see altimate-onboarding.tsx).
51-
import { DialogModelWelcome, useReady } from "../altimate-onboarding"
51+
import { DialogModelWelcome, useReady, useReadyPending } from "../altimate-onboarding"
5252
import { DialogAlert } from "../../ui/dialog-alert"
5353
import { useToast } from "../../ui/toast"
5454
import { useKV } from "../../context/kv"
@@ -268,6 +268,12 @@ export function Prompt(props: PromptProps) {
268268
// up; and flag known-bad tool-callers with a persistent "⚠ unreliable model" chip in
269269
// the prompt meta row (same WARNLIST the model picker warns with).
270270
const ready = useReady()
271+
// altimate_change — Codex HOLD finding 1: `!ready()` alone cannot distinguish "genuinely not
272+
// usable, show the picker" from "don't know yet, kv is still hydrating" — see `readyPending`'s
273+
// consumer below (`submitInner`) for why that distinction matters for a submit gate
274+
// specifically, and `useReadyPending`'s declaration in altimate-onboarding.tsx for why it's a
275+
// separate accessor rather than folded into `ready` itself.
276+
const readyPending = useReadyPending()
271277
const unreliableModel = createMemo(() => Boolean(WARNLIST[local.model.parsed().model]))
272278
// altimate_change end
273279

@@ -1027,6 +1033,23 @@ export function Prompt(props: PromptProps) {
10271033
})
10281034

10291035
let submitting = false
1036+
// altimate_change start — Codex HOLD finding 1: a submit attempted while `readyPending()` is
1037+
// true (kv still hydrating, see its declaration above) defers instead of discarding — see
1038+
// `submitInner`'s `readyPending()` branch below, which sets this flag rather than clearing the
1039+
// prompt. This effect is the retry: once `readyPending()` flips false (kv resolved either way),
1040+
// re-attempt the exact same `submit()` call automatically, so a submission made during that
1041+
// window is neither lost nor stuck waiting on the user to press Enter again. Re-running
1042+
// `submit()` (not some cached decision) means it re-evaluates `ready()` fresh against whatever
1043+
// `store.prompt.input` currently holds — if the user kept typing while deferred, that's what
1044+
// goes out; if they cleared it, `submitInner`'s own `if (!store.prompt.input) return false`
1045+
// early-exit makes this a no-op.
1046+
let deferredSubmit = false
1047+
createEffect(() => {
1048+
if (readyPending() || !deferredSubmit) return
1049+
deferredSubmit = false
1050+
void submit()
1051+
})
1052+
// altimate_change end
10301053
async function submit() {
10311054
// Prevent overlapping invocations (e.g. a double-pressed Enter, or the
10321055
// input's native onSubmit racing another dispatch). Without this guard,
@@ -1068,6 +1091,18 @@ export function Prompt(props: PromptProps) {
10681091
// message with no provider ready opens the welcome picker (the message is
10691092
// discarded) with a friendly line, rather than erroring.
10701093
if (!ready()) {
1094+
// altimate_change — Codex HOLD finding 1: `readyPending()` (see its declaration above)
1095+
// means readiness genuinely cannot be decided yet — kv is still hydrating, and none of
1096+
// `connected()`/`setupComplete()` are already true either. Discarding the prompt and
1097+
// opening the picker HERE, before kv even finishes loading, is exactly the bug: a decliner
1098+
// whose refusal lives only in kv would look un-declined for that brief window and get
1099+
// bounced into onboarding they already completed once, losing whatever they just typed.
1100+
// Defer instead — keep the prompt exactly as-is, do not open anything — and let the retry
1101+
// effect above resubmit once `readyPending()` settles.
1102+
if (readyPending()) {
1103+
deferredSubmit = true
1104+
return false
1105+
}
10711106
dialog.replace(() => (
10721107
<DialogModelWelcome
10731108
intro="First, let's connect your AI model — then I'll get right on that."

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

Lines changed: 68 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -147,24 +147,32 @@ export function isUsableFreeDefault(
147147
}
148148
// altimate_change end
149149

150-
// altimate_change start — Kilo review round 6: `hasUsableFreeDefault()`'s call site reads
151-
// `kv.get(ALTIMATE_BASE_MIGRATION_DECLINED_KEY, false)` — a default that means "not declined"
152-
// as far as `isUsableFreeDefault` above can tell, whether that's the true persisted value or
153-
// just kv hasn't hydrated yet. For a pre-0.11.x decliner whose refusal lives ONLY in kv (no
154-
// `explicitDefault` marker, no picker-written recent, and big-pickle so
150+
// altimate_change start — Kilo review round 6 / Codex HOLD finding 1: `hasUsableFreeDefault()`'s
151+
// call site reads `kv.get(ALTIMATE_BASE_MIGRATION_DECLINED_KEY, false)` — a default that means
152+
// "not declined" as far as `isUsableFreeDefault` above can tell, whether that's the true
153+
// persisted value or just kv hasn't hydrated yet. For a pre-0.11.x decliner whose refusal lives
154+
// ONLY in kv (no `explicitDefault` marker, no picker-written recent, and big-pickle so
155155
// `hasOwnPickOfImplicitDefault()` is also false — exactly the population this migration
156156
// targets), reading that default as "not declined" before kv is ready makes the WHOLE predicate
157-
// false, flips `useReady()` false, and the prompt gate (component/prompt/index.tsx) opens the
158-
// picker and discards whatever was just typed — deterministically reachable via `--prompt`
159-
// auto-submit (home.tsx waits only on `sync.ready`/`local.model.ready`, not `kv.ready`).
160-
// app.tsx's own startup decision explicitly waits on `kv.ready` before deciding anything; this
161-
// predicate cannot "wait" the same way (it must answer synchronously on every reactive read of
162-
// `useReady()`), so instead: treat an unready kv as UNDECIDED, not "not declined" — assume
163-
// usable (don't block/discard) rather than risk a false negative over a value about to flip
164-
// `true` the moment kv catches up. Extracted as a pure wrapper so the gate itself is directly
165-
// testable without mounting the full kv/model provider stack.
166-
export function hasUsableFreeDefaultGated(kvReady: boolean, computeUsable: () => boolean): boolean {
167-
if (!kvReady) return true
157+
// false. Kilo's original finding stopped there; Codex caught the first attempted fix (treat an
158+
// unready kv as "assume usable", i.e. return `true`) going the WRONG direction: that makes
159+
// `useReady()` true immediately, before onboarding/migration has had any chance to run, so
160+
// `--prompt` (or a fast manual submit) sails straight through to whatever implicit default is
161+
// currently selected — including the public Zen tier a migration disclosure should have offered
162+
// to move off of. "Assume usable" trades a false negative (discarded input) for a false positive
163+
// (skipped onboarding) — worse, not better.
164+
// The correct third state is PENDING, not `true`: an unready kv means this predicate genuinely
165+
// cannot answer yet, so it must say so explicitly rather than guessing either boolean. Callers
166+
// that only need a boolean (headless call sites, `app.tsx`'s startup effect, which already waits
167+
// on `kv.ready` before running at all) coerce `pending` to `false` — the same conservative
168+
// default the code had before kv.ready-awareness existed. The ONE caller that must NOT collapse
169+
// `pending` to `false` is the prompt submit gate (`component/prompt/index.tsx`): a `false` there
170+
// means "discard the input and open the picker", which is exactly the data-loss bug this was
171+
// supposed to fix. `useReadyPending()` (see `altimate-onboarding.tsx`) is the seam that lets the
172+
// submit gate DEFER — keep the typed prompt, don't judge yet, retry once kv actually resolves —
173+
// instead of discarding it over an answer that was never computed.
174+
export function hasUsableFreeDefaultGated(kvReady: boolean, computeUsable: () => boolean): boolean | "pending" {
175+
if (!kvReady) return "pending"
168176
return computeUsable()
169177
}
170178
// altimate_change end
@@ -699,9 +707,11 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
699707
// after a deliberate pick, flipping `useReady()` true→false and reopening the picker (and
700708
// clearing the prompt) on the very next submit.
701709
//
702-
// altimate_change — Kilo review round 6: gated through `hasUsableFreeDefaultGated` — see
703-
// its declaration above — so an unready `kv` reads as undecided (assume usable) rather
704-
// than "not declined."
710+
// altimate_change — Kilo review round 6 / Codex HOLD finding 1: gated through
711+
// `hasUsableFreeDefaultGated` — see its declaration above — so an unready `kv` reads as
712+
// `"pending"` (genuinely undecided), not a boolean guess either way. Callers that need a
713+
// plain boolean coerce it (`=== true`); `useReadyPending()` in altimate-onboarding.tsx is
714+
// the one caller (the prompt submit gate) that must see the `"pending"` state itself.
705715
return hasUsableFreeDefaultGated(kv.ready, () => (
706716
isUsableFreeDefault(
707717
currentModel(),
@@ -742,6 +752,13 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
742752
}
743753
// altimate_change end
744754

755+
// altimate_change start — Codex HOLD finding 2: `cycle()`'s traversal order, captured
756+
// lazily on first use and held stable for the rest of the cycling sequence — see
757+
// `cycle()`'s own comment below for why a LIVE read of `modelStore.recent` (which `cycle()`
758+
// itself reorders via `selectModel(val, { recent: true })`) breaks repeated presses.
759+
let cycleOrder: readonly { providerID: string; modelID: string }[] | undefined
760+
// altimate_change end
761+
745762
return {
746763
current: currentModel,
747764
get ready() {
@@ -767,37 +784,46 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
767784
return modelDisplayName(currentModel())
768785
}),
769786
// altimate_change end
787+
// altimate_change start — PR #1302 review, cubic P2 (round 6: also pass `recent: true`,
788+
// like `cycleFavorite` below) / Codex HOLD finding 2 (round 7: stable traversal order).
789+
// Two requirements that pull in opposite directions if both aimed at the SAME array:
790+
// 1. Cycling must move the picked model to the front of PERSISTED `recent` — that's the
791+
// ONLY state headless/ACP default resolution (`Provider.readDefaultModelState()`,
792+
// `defaultModelFromConfig()`) reads; without it the TUI and server can resolve two
793+
// different launch defaults from the same `model.json` after a cycle (they have no
794+
// notion of the earlier `explicitDefault`-only marker this used to rely on instead).
795+
// 2. Cycling must visit every model in a stable order across repeated presses — reading
796+
// the INDEX to advance from directly off that same, just-reordered `modelStore.recent`
797+
// breaks this: cycling forward from B in [A, B, C] persists [B, A, C], so the NEXT
798+
// forward press finds B now at index 0 (not 1) and its "next" becomes A — landing
799+
// B → A → B forever instead of visiting every model (Codex caught this by actually
800+
// executing it: HEAD's behavior was B → A → B; the correct behavior, matching the
801+
// order before any cycling started, is B → C → A).
802+
// `cycleOrder` (declared above, alongside `modelStore`) resolves this: it is a SEPARATE,
803+
// stable snapshot of `recent`'s order, captured lazily on first use and held fixed for
804+
// the rest of the cycling sequence — `cycle()`'s own index math walks THIS frozen list,
805+
// never the live, self-reordering `modelStore.recent`. `selectModel(..., { recent: true })`
806+
// still updates the real persisted `recent` on every pick, satisfying requirement 1; it
807+
// just no longer feeds back into what `cycle()` itself reads for requirement 2. If the
808+
// current model isn't found in the captured order (the user picked something else via
809+
// `/model` since cycling last started, or this is the very first cycle this session),
810+
// (re-)capture fresh from the CURRENT `modelStore.recent` and start the sequence there.
770811
cycle(direction: 1 | -1) {
771812
const current = currentModel()
772813
if (!current) return
773-
const recent = modelStore.recent
774-
const index = recent.findIndex((x) => x.providerID === current.providerID && x.modelID === current.modelID)
814+
const findCurrent = (order: readonly { providerID: string; modelID: string }[]) =>
815+
order.findIndex((x) => x.providerID === current.providerID && x.modelID === current.modelID)
816+
if (!cycleOrder || findCurrent(cycleOrder) === -1) cycleOrder = modelStore.recent.slice()
817+
const index = findCurrent(cycleOrder)
775818
if (index === -1) return
776819
let next = index + direction
777-
if (next < 0) next = recent.length - 1
778-
if (next >= recent.length) next = 0
779-
const val = recent[next]
820+
if (next < 0) next = cycleOrder.length - 1
821+
if (next >= cycleOrder.length) next = 0
822+
const val = cycleOrder[next]
780823
if (!val) return
781-
// altimate_change start — PR #1302 review, cubic P2 (round 6: also pass `recent: true`,
782-
// like `cycleFavorite` below): route through `selectModel` so this deliberate keyboard
783-
// pick also marks `explicitDefault` AND moves the cycled-to model to the front of
784-
// `recent`. Without the explicit marker, an all-free-tier user who cycles onto a free
785-
// Zen model stays "implicit" per `hasExplicitDefault()`/`hasUsableFreeDefault()`, and
786-
// the first-run picker reopens on every later launch even though they chose it on
787-
// purpose. `recent: true` used to be deliberately omitted here (to keep `cycle()`'s own
788-
// index-based navigation order stable across repeated presses) — but `recent` is the
789-
// ONLY thing headless/ACP default resolution (`Provider.readDefaultModelState()`,
790-
// `defaultModelFromConfig()`) reads; they have no notion of `explicitDefault`. Omitting
791-
// `recent: true` let the TUI and server resolve two different launch defaults from the
792-
// same `model.json` after a cycle. Reordering `recent` on every cycle does mean
793-
// `cycle()`'s own index computation above now walks a list that just reshuffled — a
794-
// repeated cycle in the same direction can revisit an entry sooner than before — but
795-
// that's a minor UX quirk against a real cross-surface correctness bug, and it keeps
796-
// `recent` the single source of truth everywhere instead of teaching the server about a
797-
// second, TUI-only marker.
798824
selectModel(val, { explicit: true, recent: true })
799-
// altimate_change end
800825
},
826+
// altimate_change end
801827
cycleFavorite(direction: 1 | -1) {
802828
const favorites = modelStore.favorite.filter((item) => isModelValid(item))
803829
if (!favorites.length) {

0 commit comments

Comments
 (0)