GeezerVison is showing github.com — fix(core): recover Console models after startup failures by kitlangton · Pull Request #45759 · anomalyco/opencode
fix(core): recover Console models after startup failures
#45759
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.md
(1)
.ts
(8)
All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
fix(core): recover Console models after startup failures
A transient Console configuration fetch failure was swallowed into an empty inventory that stayed captured after networking recovered. Refresh sources separately from catalog replay, retry transient loads within a bounded startup budget, and recover failed inventories in the background with capped backoff.
Preserve same-account inventory, refresh missing selections and moved sessions, and cover startup recovery, account isolation, cancellation, and ordered policy replay with production-service tests.
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
commit b70bdad05310a3eaef19076aae6083f4e523ce02
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,5 @@
---
"@opencode-ai/core": patch
---
Recover Console model inventories after transient startup failures without restarting the service. Retry failed source loads, refresh missing selections and moved sessions, and retain the last successful inventory only for the same account.
Original file line number
Diff line number
Diff line change
@@ -1,7 +1,7 @@
export * as Catalog from "./catalog.js"
import { makeLocationNode } from "@opencode-ai/util/effect/app-node"
import { Array, Context, Effect, Layer, Order, pipe } from "effect"
import { Array, Context, Effect, Layer, Order, pipe, Scope, Semaphore } from "effect"
import { Catalog } from "@opencode-ai/schema/catalog"
import { Model } from "./model.js"
import { Provider } from "./provider.js"
Expand Down
Expand Up
@@ -42,6 +42,9 @@ export type Draft = {
}
export interface Interface extends State.Transformable<Draft> {
/** Internal sources update captured data and report whether ordered transforms need replaying. */
readonly onRefresh: (source: () => Effect.Effect<boolean>) => Effect.Effect<void, never, Scope.Scope>
readonly refresh: () => Effect.Effect<void>
readonly provider: {
readonly get: (providerID: Provider.ID) => Effect.Effect<Provider.Info | undefined>
readonly all: () => Effect.Effect<Provider.Info[]>
Expand All
@@ -63,6 +66,8 @@ const layer = Layer.effect(
Effect.gen(function* () {
const bus = yield* Bus.Service
const integrations = yield* Integration.Service
const sources = new Set<() => Effect.Effect<boolean>>()
const refreshing = Semaphore.makeUnsafe(1)
const available = (provider: Provider.Info, integration: Integration.Info | undefined) => {
if (provider.activation === "disabled") return false
Expand Down
Expand Up
@@ -138,9 +143,27 @@ const layer = Layer.effect(
yield* bus.publish(Catalog.Event.Updated, {})
}),
})
const refresh = Effect.fn("Catalog.refresh")(() =>
refreshing.withPermit(
Effect.gen(function* () {
const changed = yield* Effect.forEach(sources, (source) => source())
// Keep the permit until captured changes are visible, even if the caller is interrupted.
if (changed.some(Boolean)) yield* state.reload().pipe(Effect.uninterruptible)
}),
),
)
const result: Interface = {
transform: state.transform,
reload: state.reload,
onRefresh: (source) =>
Effect.acquireRelease(
Effect.sync(() => sources.add(source)),
() =>
Effect.sync(() => {
sources.delete(source)
}),
).pipe(Effect.asVoid),
refresh,
provider: {
get: Effect.fn("Catalog.provider.get")(function* (providerID) {
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -39,6 +39,7 @@ import { SessionRunnerLLM } from "./session/runner/llm.js"
import { SessionRunnerModel } from "./session/runner/model.js"
import { SessionModelTransport } from "./session/model-transport.js"
import { SessionCompaction } from "./session/compaction.js"
import { SessionContext } from "./session/context.js"
import { SessionTitle } from "./session/title.js"
import { Skill } from "./skill.js"
import { SkillInstructions } from "./skill/instructions.js"
Expand Down
Expand Up
@@ -98,6 +99,7 @@ const locationServiceNodes = [
ReadToolFileSystem.node,
McpTool.node,
SessionInstructions.node,
SessionContext.node,
SessionRunnerModel.node,
SessionModelTransport.node,
SessionCompaction.node,
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,9 +1,10 @@
import { Duration, Effect, Schema, Semaphore , Stream } from "effect"
import { Cause, Duration, Effect, Schedule, Schema , Stream } from "effect"
import type { Scope } from "effect"
import type { IntegrationOAuthMethodRegistration } from "@opencode-ai/plugin/effect/integration"
import { define } from "@opencode-ai/plugin/effect/plugin"
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"
import { Bus } from "../../bus.js"
import { Catalog } from "../../catalog.js"
import { Credential } from "../../credential.js"
import { Integration } from "../../integration.js"
import { Model } from "../../model.js"
Expand All
@@ -12,6 +13,8 @@ import { ConfigProviderV1 } from "../../v1/config/provider.js"
import { Money } from "@opencode-ai/schema/money"
import { ConfigProviderOptionsV1 } from "../../v1/config/provider-options.js"
import { ConfigV1 } from "../../v1/config/config.js"
import { SessionEvent } from "../../session/event.js"
import { isDeepStrictEqual } from "node:util"
const defaultServer = "https://opencode.ai/console"
const clientID = "opencode-cli"
Expand Down
Expand Up
@@ -82,28 +85,43 @@ function oauth(http: HttpClient.HttpClient) {
} satisfies IntegrationOAuthMethodRegistration
}
export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope.Scope>({
export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Catalog.Service | Scope.Scope>({
id: "opencode.provider.opencode",
effect: Effect.fn(function* (ctx) {
const bus = yield* Bus.Service
const catalog = yield* Catalog.Service
const http = yield* HttpClient.HttpClient
const loading = Semaphore.makeUnsafe(1)
let connected = false
let providers: typeof ConfigV1.Info.Type.provider | undefined
let source: string | undefined
let retrying = false
const load = Effect.fn("OpencodePlugin.load")(function* () {
const connection = yield* ctx.integration.connection.active("opencode")
const credential = connection
? yield* ctx.integration.connection.resolve(connection).pipe(Effect.orElseSucceed(() => undefined))
: undefined
connected = connection !== undefined
providers = credential
? yield* fetchProviders(http, credential).pipe(
Effect.catch((cause) =>
Effect.logWarning("failed to load OpenCode provider config", { cause }).pipe(Effect.as(undefined)),
const id = connection?.type === "credential" ? connection.id : connection?.name
const next = connection
? yield* ctx.integration.connection.resolve(connection).pipe(
Effect.flatMap((credential) => (credential ? fetchProviders(http, credential) : Effect.undefined)),
Effect.retry({ while: retryable, times: 2, schedule: Schedule.exponential(200) }),
Effect.timeout("5 seconds"),
Effect.tap(() =>
Effect.sync(() => {
retrying = false
}),
),
Effect.catch((cause) => {
retrying = retryable(cause)
// Retain inventory through same-account outages, never across an account switch.
return Effect.logWarning("failed to load OpenCode provider config", { cause }).pipe(
Effect.as(id === source ? providers : undefined),
)
}),
)
: undefined
if (!connection) retrying = false
const changed = source !== id || !isDeepStrictEqual(providers, next)
source = id
providers = next
return changed
})
yield* ctx.integration.transform((draft) => {
Expand Down
Expand Up
@@ -176,7 +194,7 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
const item = catalog.provider.get(Provider.ID.opencode)
if (!item) return
const hasKey = Boolean(process.env.OPENCODE_API_KEY || connected || item.provider.settings?.apiKey)
const hasKey = Boolean(process.env.OPENCODE_API_KEY || source !== undefined || item.provider.settings?.apiKey)
catalog.provider.update(item.provider.id, (provider) => {
if (!hasKey) {
provider.activation = "enabled"
Expand All
@@ -192,15 +210,40 @@ export const OpencodePlugin = define<HttpClient.HttpClient | Bus.Service | Scope
}
})
const refresh = () => loading.withPermit(load().pipe(Effect.andThen(ctx.catalog.reload())))
yield* bus.subscribe(Credential.Event.Switched).pipe(
Stream.filter((event) => event.data.integrationID === Integration.ID.make("opencode")),
Stream.runForEach(refresh),
yield* catalog.onRefresh(load)
yield* bus.subscribe([Credential.Event.Switched, SessionEvent.Moved]).pipe(
Stream.filter((event) =>
event.type === "credential.switched"
? event.data.integrationID === Integration.ID.make("opencode")
: event.data.location.directory === ctx.location.directory &&
event.data.location.workspaceID === ctx.location.workspaceID,
),
Stream.runForEach(() => catalog.refresh()),
Effect.forkScoped({ startImmediately: true }),
)
// A failed startup must recover even when no session or account action triggers another lookup.
let delay = 5_000
yield* Effect.gen(function* () {
yield* Effect.sleep(delay)
if (retrying) yield* catalog.refresh()
delay = retrying ? Math.min(delay * 2, 30_000) : 5_000
}).pipe(Effect.forever, Effect.forkScoped)
}),
})
function retryable(cause: unknown): boolean {
if (cause instanceof Integration.AuthorizationError) return retryable(cause.cause)
if (Cause.isTimeoutError(cause)) return true
if (!HttpClientError.isHttpClientError(cause)) return false
return (
cause.reason._tag === "TransportError" ||
(cause.reason._tag === "StatusCodeError" &&
(cause.reason.response.status === 408 ||
cause.reason.response.status === 429 ||
cause.reason.response.status >= 500))
)
}
function fetchProviders(http: HttpClient.HttpClient, value: Credential.Value) {
const metadata = value.metadata
const server = typeof metadata?.server === "string" ? metadata.server : defaultServer
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -91,7 +91,15 @@ const layer = Layer.effect(
const store = yield* SessionStore.Service
const registry = yield* Tool.Service
const resolveModel = (session: SessionSchema.Info) => models.resolve(session, catalog.model.available)
const resolveModel = Effect.fn("SessionContext.resolveModel")(function* (session: SessionSchema.Info) {
const resolve = models.resolve(session, catalog.model.available)
// Retry once against a refreshed inventory without bypassing Location policy.
return yield* resolve.pipe(
Effect.catchTag("SessionRunnerModel.ModelUnavailableError", () =>
catalog.refresh().pipe(Effect.andThen(resolve)),
),
)
})
const selectTitle = Effect.fn("SessionContext.selectTitle")(function* (session: SessionSchema.Info) {
const agent = yield* agents.get(Agent.ID.make("title"))
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -30,6 +30,70 @@ const catalogLayer = AppNodeBuilder.build(
const it = testEffect(catalogLayer)
describe("Catalog", () => {
it.effect("refreshes scoped sources and replays only changed snapshots", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const source = { fresh: false, calls: 0 }
yield* catalog.transform((draft) => {
if (!source.fresh) return
draft.model.update(Provider.ID.make("example"), Model.ID.make("chat"), () => {})
draft.model.default.set(Provider.ID.make("example"), Model.ID.make("chat"))
})
yield* Effect.scoped(
Effect.gen(function* () {
yield* catalog.onRefresh(() =>
Effect.sync(() => {
source.calls++
if (source.fresh) return false
source.fresh = true
return true
}),
)
expect(yield* catalog.model.default()).toBeUndefined()
const refresh = yield* catalog.refresh().pipe(Effect.forkScoped)
yield* TestClock.adjust("1 second")
yield* Fiber.join(refresh)
expect((yield* catalog.model.default())?.id).toBe(Model.ID.make("chat"))
expect(source.calls).toBe(1)
yield* catalog.refresh()
expect(source.calls).toBe(2)
}),
)
yield* catalog.refresh()
expect(source.calls).toBe(2)
}),
)
it.effect("finishes replay before releasing an interrupted refresh", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
const source = { fresh: false }
yield* catalog.transform((draft) => {
if (source.fresh) draft.model.update(Provider.ID.make("example"), Model.ID.make("chat"), () => {})
})
yield* catalog.onRefresh(() =>
Effect.sync(() => {
if (source.fresh) return false
source.fresh = true
return true
}),
)
const refresh = yield* catalog.refresh().pipe(Effect.forkScoped({ startImmediately: true }))
yield* TestClock.adjust("0 millis")
const interrupted = yield* Fiber.interrupt(refresh).pipe(Effect.forkScoped({ startImmediately: true }))
yield* TestClock.adjust("0 millis")
const retry = yield* catalog.refresh().pipe(Effect.forkScoped({ startImmediately: true }))
yield* TestClock.adjust("0 millis")
expect(retry.pollUnsafe()).toBeUndefined()
yield* TestClock.adjust("1 second")
yield* Fiber.join(interrupted)
yield* Fiber.join(retry)
expect((yield* catalog.model.get(Provider.ID.make("example"), Model.ID.make("chat")))?.id).toBe(
Model.ID.make("chat"),
)
}),
)
it.effect("publishes an updated event after catalog changes", () =>
Effect.gen(function* () {
const catalog = yield* Catalog.Service
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.