Skip to content

Commit 3a975b4

Browse files
fix: keep the rejected-to-restored reload, cycle off explicit Zen, and pin the concurrency test
- The register route reads the credential before registering again and compares it inside the serialized section, so a rejected credential restored with identical fields still reloads. New test covers it. - `cycle()` keeps keyless-Zen entries as-is when the current model is an explicit Zen pick, which `currentModel()` honors, so cycling can move away from it. New test covers it. - The concurrency test waits for both requests to pass registration and for the first disposal to start before releasing it, instead of a fixed sleep. It fails without the serialization. - Test fixture: rename a mock provider to avoid a product-name leak. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_016x3nbZU5Vb6HnSTqE7vELm
1 parent 13c5c78 commit 3a975b4

4 files changed

Lines changed: 91 additions & 18 deletions

File tree

‎packages/opencode/src/server/server.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -783,6 +783,9 @@ export namespace Server {
783783
)
784784
}
785785

786+
// Read before registering: a credential that was rejected, expired or logged out and is
787+
// now reissued with identical fields still has to reload, and only this read sees that.
788+
const before = await FreeTier.credentials().catch(() => undefined)
786789
const gate = FreeTierConsent.createRegistrationGate({
787790
register: () => FreeTier.register({ origin: "server" }),
788791
onUnexpectedError: (error) => log.error("Altimate Base registration failed", { error }),
@@ -818,15 +821,17 @@ export namespace Server {
818821
// The check and the reload run one at a time, so two concurrent calls cannot both pass
819822
// the check and dispose the same live resources twice; the second sees the first's mark.
820823
if (outcome.ok) {
821-
const reload = baseReloadQueue.then(async () => {
822-
const current = await FreeTier.credentials().catch(() => undefined)
823-
// Identity covers everything that decides whether a loader sees Base: an expired or
824-
// rejected credential loads as absent, and a logout elsewhere rotates the nonce, so the
825-
// same key and URL reissued after either still has to reload.
826-
const fingerprint = current
827-
? [current.baseURL, current.apiKey, current.expiresAt ?? "", current.rejected ? "rejected" : "", current.logoutNonce ?? ""].join("\n")
824+
// Identity covers everything that decides whether a loader sees Base: an expired or
825+
// rejected credential loads as absent, and a logout elsewhere rotates the nonce, so the
826+
// same key and URL reissued after either still has to reload.
827+
const identity = (value: typeof before) =>
828+
value
829+
? [value.baseURL, value.apiKey, value.expiresAt ?? "", value.rejected ? "rejected" : "", value.logoutNonce ?? ""].join("\n")
828830
: undefined
829-
if (fingerprint !== undefined && fingerprint === appliedBaseCredential) return true
831+
const reload = baseReloadQueue.then(async () => {
832+
const fingerprint = identity(await FreeTier.credentials().catch(() => undefined))
833+
const changed = identity(before) !== fingerprint
834+
if (!changed && fingerprint !== undefined && fingerprint === appliedBaseCredential) return true
830835
const disposed = await Promise.all([
831836
Instance.disposeAll().then(
832837
() => true,

‎packages/opencode/test/server/altimate-base-registration.test.ts‎

Lines changed: 49 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -236,13 +236,28 @@ describe("Altimate Base registration route", () => {
236236
test("two concurrent register calls reload once", async () => {
237237
const shared = { apiKey: "sk-concurrent", baseURL: "https://gateway.test", installSecret: "s" }
238238
mockCredentialsSequence(shared)
239-
mockRegister(async () => shared)
239+
// Both requests must be past registration before either reloads, so they genuinely overlap.
240+
let entered = 0
241+
let bothEntered!: () => void
242+
const overlap = new Promise<void>((resolve) => {
243+
bothEntered = resolve
244+
})
245+
mockRegister(async () => {
246+
if (++entered === 2) bothEntered()
247+
await overlap
248+
return shared
249+
})
240250
let release!: () => void
241251
const held = new Promise<void>((resolve) => {
242252
release = resolve
243253
})
244-
// Hold the first disposal open so the second request arrives while it is still in flight.
254+
let firstDisposeStarted!: () => void
255+
const disposing = new Promise<void>((resolve) => {
256+
firstDisposeStarted = resolve
257+
})
258+
// Hold the first disposal open while the second request is already waiting behind it.
245259
const disposeAll = spyOn(Instance, "disposeAll").mockImplementation(async () => {
260+
firstDisposeStarted()
246261
await held
247262
})
248263
const post = () =>
@@ -252,11 +267,11 @@ describe("Altimate Base registration route", () => {
252267
body: JSON.stringify({}),
253268
})
254269
try {
255-
const first = post()
256-
const second = post()
257-
await Bun.sleep(50)
270+
const requests = [post(), post()]
271+
await overlap
272+
await disposing
258273
release()
259-
const bodies = await Promise.all([first, second].map(async (r) => (await r).json()))
274+
const bodies = await Promise.all(requests.map(async (r) => (await r).json()))
260275
for (const body of bodies) expect(body).toMatchObject({ ok: true })
261276
expect(disposeAll).toHaveBeenCalledTimes(1)
262277
} finally {
@@ -265,6 +280,34 @@ describe("Altimate Base registration route", () => {
265280
}
266281
})
267282

283+
test("reloads when a rejected credential is restored with identical fields", async () => {
284+
// Directories opened while the credential was rejected cached no Base; clearing the flag can
285+
// reissue exactly the credential this process reloaded for before it was rejected.
286+
const good = { apiKey: "sk-rejected", baseURL: "https://gateway.test", installSecret: "s" }
287+
const rejected = { ...good, rejected: true }
288+
const disposeAll = spyOn(Instance, "disposeAll")
289+
const post = () =>
290+
app().request("/altimate/base/register", {
291+
method: "POST",
292+
headers: { "content-type": "application/json" },
293+
body: JSON.stringify({}),
294+
})
295+
try {
296+
mockCredentialsSequence(good)
297+
mockRegister(async () => good)
298+
await post()
299+
expect(disposeAll).toHaveBeenCalledTimes(1)
300+
credentialsSpy?.mockRestore()
301+
registerSpy?.mockRestore()
302+
mockCredentialsSequence(rejected, good)
303+
mockRegister(async () => good)
304+
expect(await (await post()).json()).toMatchObject({ ok: true })
305+
expect(disposeAll).toHaveBeenCalledTimes(2)
306+
} finally {
307+
disposeAll.mockRestore()
308+
}
309+
})
310+
268311
test("reloads for a credential registered in the background, even if one directory already sees Base", async () => {
269312
// A startup auto-registration that finished after the server started leaves the file unchanged
270313
// across this request, while caches built earlier (another directory, or the /api registry)

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -917,10 +917,14 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
917917
order.findIndex((x) => x.providerID === current.providerID && x.modelID === current.modelID)
918918
if (!cycleOrder || cycleOrderVersion !== recentsVersion || findCurrent(cycleOrder) === -1) {
919919
// Resolve stale keyless-Zen entries to Base the same way `currentModel()` does, so a
920-
// repaired current model is found in the order and Zen is never cycled back onto.
920+
// repaired current model is found in the order and Zen is never cycled back onto. An
921+
// explicit Zen pick (`--model`, config, agent) stays Zen in `currentModel()`, so the
922+
// order keeps Zen as-is then, or cycling could not find it to move away.
923+
const currentProvider = sync.data.provider.find((candidate) => candidate.id === current.providerID)
924+
const keepZen = !!currentProvider && isPublicZenProvider(currentProvider)
921925
const seen = new Set<string>()
922926
cycleOrder = modelStore.recent.flatMap((entry) => {
923-
const resolved = substituteStaleZen(entry) ?? entry
927+
const resolved = keepZen ? entry : (substituteStaleZen(entry) ?? entry)
924928
const key = `${resolved.providerID}/${resolved.modelID}`
925929
if (seen.has(key)) return []
926930
seen.add(key)

‎packages/tui/test/context/stale-zen-cycle.test.tsx‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ function makeModel(id: string, providerID = "opencode") {
3535
}
3636
}
3737

38-
async function mount() {
38+
async function mount(agentModel?: { providerID: string; modelID: string }) {
3939
const [
4040
{ KVProvider },
4141
{ LocalProvider, useLocal },
@@ -71,7 +71,7 @@ async function mount() {
7171

7272
const zenProvider = {
7373
id: "opencode",
74-
name: "OpenCode Zen",
74+
name: "Zen",
7575
options: { apiKey: "public" },
7676
models: { "model-a": makeModel("model-a") },
7777
env: [],
@@ -95,6 +95,7 @@ async function mount() {
9595
hidden: false,
9696
permission: {},
9797
options: {},
98+
...(agentModel ? { model: agentModel } : {}),
9899
}
99100
const inner = createFetch((url) => {
100101
if (url.pathname === "/instance/dispose") return json({})
@@ -155,6 +156,26 @@ async function mount() {
155156
}
156157

157158

159+
test("cycle() still moves off an explicitly chosen keyless-Zen model", async () => {
160+
const originalStateHome = process.env.OPENCODE_TEST_STATE_HOME
161+
await using isolatedState = await tmpdir()
162+
process.env.OPENCODE_TEST_STATE_HOME = isolatedState.path
163+
// The agent's own configured model is explicit, so `currentModel()` keeps it as Zen.
164+
const { local, cleanup } = await mount(STALE_ZEN)
165+
try {
166+
await waitUntil(() => local.model.ready)
167+
await waitUntil(() => local.model.current()?.providerID === STALE_ZEN.providerID)
168+
await Bun.sleep(100)
169+
expect(local.model.current()?.providerID).toBe(STALE_ZEN.providerID)
170+
local.model.cycle(1)
171+
await waitUntil(() => local.model.current()?.modelID === OWN.modelID)
172+
} finally {
173+
await cleanup()
174+
if (originalStateHome === undefined) delete process.env.OPENCODE_TEST_STATE_HOME
175+
else process.env.OPENCODE_TEST_STATE_HOME = originalStateHome
176+
}
177+
})
178+
158179
test("cycle() moves off a Base model that replaced a stale keyless-Zen recent", async () => {
159180
const originalStateHome = process.env.OPENCODE_TEST_STATE_HOME
160181
await using isolatedState = await tmpdir()

0 commit comments

Comments
 (0)