GeezerVison is showing github.com — fix(tui,app): only apply extended 5min retry to ServiceUnavailableError location sync by cxxde · Pull Request #61547 · anomalyco/opencode
fix(tui,app): only apply extended 5min retry to ServiceUnavailableError location sync
#61547
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
.ts
(4)
.tsx
(3)
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 :
#46 tui: cold load of a UNC location returns 503 for agent/model…
…/provider, prompt cannot be sent #61359
Bug: #46
Changelog-Bug: 修复冷启动(如 Windows UNC 路径)时 TUI 对 /api/agent、/api/model、/api/provider 的初始目录同步只重试 3 次的问题:服务端插件激活期间每个请求约 5 秒后返回 503,重试预算约 16 秒耗尽后失败被静默吞掉,agent/model 列表永久为空,提示无法发送、shift+tab 切换 agent 无效。现在初始同步在 5 分钟预算内按 1-5 秒退避持续重试;客户端在收到已请求位置的 agent/model/provider.updated 事件时补做完整同步,位置预热完成即自动恢复;预算用尽仍失败时显示错误提示而不是静默禁用输入。Web 端应用相同重试预算。
Loading branch information
Uh oh!
There was an error while loading. Please reload this page.
gitlab-aibot
committed
Nov 3, 2026
commit 77868db652dec52baf88ba25e3365b1caa0aad87
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -45,7 +45,11 @@ const context = createSimpleContext({
if (serverSDK.connection.status() !== "connected") return
// Generic sync failures do not prove the directory is missing; only the server's typed
// LocationNotFoundError does, and retrying it cannot succeed until the folder changes.
// A cold Location answers with 503 while its plugins activate, so keep retrying until it warms up.
void retry(() => (stale ? Promise.resolve() : data.location.sync(location)), {
delay: 1_000,
maxDelay: 5_000,
timeout: 5 * 60 * 1000,
retryIf: (error) => !stale && !isLocationNotFoundError(error),
}).catch((error) => {
if (stale || !isLocationNotFoundError(error)) return
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -1350,12 +1350,15 @@ export function createData(config: CreateDataInput) {
const location = event.location
switch (event.type) {
case "provider.updated":
bootstrapLocation(location)
refreshLocation("provider", result.location.provider, location)
break
case "model.updated":
bootstrapLocation(location)
refreshLocation("model", result.location.model, location)
break
case "agent.updated":
bootstrapLocation(location)
refreshLocation("agent", result.location.agent, location)
break
case "command.updated":
Expand Down
Expand Up
@@ -1448,6 +1451,18 @@ export function createData(config: CreateDataInput) {
if (active) refresh(() => resource.sync(location))
}
// A cold Location answers catalog reads with 503 while its plugins activate, so an initial sync can
// fail before anything was stored. When the Location finishes booting it publishes these catalog
// events; bootstrap the whole Location instead of dropping them, otherwise the failed sync never recovers.
function bootstrapLocation(location: LocationRef) {
// syncInfo creates the `info` entry before the catalog reads; a location without it was only ever
// touched by an individual resource (e.g. vcs), so its catalog event is not a dropped full sync.
if (!store.location[locationKey(location)]?.info) return
const loaded = ["agent", "model", "provider"] as const
if (loaded.some((field) => hasLocation(field, location))) return
refresh(() => result.location.sync(location))
}
// A cached per-location catalog. `sync` loads once per invalidation, keyed by the
// effective location, and publishes under the server's canonical location; `alias`
// also publishes under the requested key when the two differ.
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -939,6 +939,67 @@ test("ignores catalog updates for unloaded locations while refreshing loaded loc
}
})
test("bootstraps a requested location when its first catalog sync failed with 503", async () => {
const listeners = new Set<Parameters<CreateDataInput["event"]["listen"]>[0]>()
const location = { directory: "/cold", project: { id: "cold", directory: "/cold", canonical: "/cold" } }
const requests: string[] = []
let warmed = false
const serviceUnavailable = () =>
new Response(JSON.stringify({ _tag: "ServiceUnavailableError", message: "Location plugins did not finish activating", service: "plugin" }), {
status: 503,
headers: { "content-type": "application/json" },
})
const api = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: async (input, init) => {
const request = input instanceof Request ? input : new Request(input, init)
const url = new URL(request.url)
requests.push(url.pathname)
if (url.pathname === "/api/location") return Response.json(location)
// Cold Location: catalog endpoints return 503 until it warms up.
if (["/api/agent", "/api/model", "/api/provider"].includes(url.pathname) && !warmed)
return serviceUnavailable()
const empty =
url.pathname === "/api/vcs"
? { branch: {} }
: url.pathname === "/api/mcp/resource"
? { resources: [] }
: []
return Response.json({ location, data: empty })
},
})
const setup = createRoot((dispose) => ({
data: createData({
api: () => api,
directory: "/cold",
event: {
on: () => () => {},
listen(handler) {
listeners.add(handler)
return () => listeners.delete(handler)
},
},
connection: { status: () => "connected" },
}),
dispose,
}))
const emit = (details: OpenCodeEvent) => listeners.forEach((listener) => listener({ name: details.type, details }))
try {
await setup.data.location.syncInfo()
await expect(setup.data.location.agent.sync()).rejects.toMatchObject({ _tag: "ServiceUnavailableError" })
expect(setup.data.location.agent.list()).toBeUndefined()
// The Location finishes booting and announces its catalog. The dropped sync must recover.
warmed = true
emit({ id: "evt_agent_updated", created: 1, type: "agent.updated", location, data: {} })
await wait(() => setup.data.location.agent.list() !== undefined)
expect(requests).toContain("/api/agent")
} finally {
setup.dispose()
}
})
test("revalidates model discovery when an update overtakes an in-flight model list", async () => {
const started = Promise.withResolvers<void>()
const release = Promise.withResolvers<void>()
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,8 +1,14 @@
import { isLocationNotFoundError, type LocationGetOutput, type LocationRef } from "@opencode/client"
import {
isLocationNotFoundError,
isServiceUnavailableError,
type LocationGetOutput,
type LocationRef,
} from "@opencode/client"
import { retry } from "@opencode/util/retry"
import { createContext, createMemo, createSignal, onCleanup, useContext, type ParentProps } from "solid-js"
import { useClient } from "./client"
import { useData } from "./data"
import { useToastOptional } from "../ui/toast"
const context = createContext<{
readonly current: LocationGetOutput | undefined
Expand All
@@ -12,9 +18,15 @@ const context = createContext<{
set: (location?: LocationRef) => void
}>()
// A cold Location, e.g. a Windows UNC path, can take longer than the server's 5s plugin activation
// deadline to boot, and each catalog request returns 503 in the meantime. Keep retrying until the
// Location warms up rather than giving up after three attempts and leaving the composer dead.
const LOCATION_READY_TIMEOUT = 5 * 60 * 1000
export function LocationProvider(props: ParentProps) {
const client = useClient()
const data = useData()
const toast = useToastOptional()
const [ref, setRef] = createSignal<LocationRef>()
const [error, setError] = createSignal<{ readonly location: LocationRef; readonly cause: unknown }>()
let generation = 0
Expand All
@@ -30,19 +42,29 @@ export function LocationProvider(props: ParentProps) {
: location
setError(undefined)
// Only the server's typed LocationNotFoundError proves the folder is gone. Other failures, such as
// plugins still activating after a restart, are retried and never block the composer .
// 503s while plugins are still activating after a restart, are retried until the Location warms up .
void retry(() => (generation === attempt ? data.location.sync(target) : Promise.resolve()), {
delay: 1_000,
maxDelay: 5_000,
timeout: LOCATION_READY_TIMEOUT,
retryIf: (cause) => generation === attempt && !isLocationNotFoundError(cause),
Comment thread
cxxde marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
}).catch((cause) => {
const current = ref()
if (
!isLocationNotFoundError(cause) ||
const stale =
generation !== attempt ||
current?.directory !== location.directory ||
current.workspaceID !== location.workspaceID
)
if (stale) return
if (isLocationNotFoundError(cause)) {
setError({ location, cause })
return
setError({ location, cause })
}
// The catalog never loaded, so the prompt cannot send. Say so instead of failing silently.
if (isServiceUnavailableError(cause)) {
toast?.error(`${cause.message}. Check the server logs, then run /reload to retry.`)
} else {
toast?.error(cause)
}
})
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -220,3 +220,8 @@ export function useToast() {
}
return value
}
// Providers mounted above the ToastProvider in the tree, such as LocationProvider, use this.
export function useToastOptional() {
return useContext(ctx)
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -71,6 +71,36 @@ describe("client retry", () => {
expect(failures).toHaveLength(1)
})
test("keeps retrying past the attempt count until the timeout budget expires", async () => {
const startedAt = Date.now()
const failures: string[] = []
await expect(
retry(
async () => {
failures.push("attempt")
throw new Error("retry me")
},
{ attempts: 2, delay: 10, factor: 1, timeout: 100, retryIf: () => true },
),
).rejects.toThrow("retry me")
expect(Date.now() - startedAt).toBeGreaterThanOrEqual(90)
expect(failures.length).toBeGreaterThan(2)
})
test("succeeds within the timeout even after more failures than the attempt count", async () => {
const failures: string[] = []
const value = await retry(
async () => {
failures.push("attempt")
if (failures.length < 5) throw new Error("retry me")
return "ready"
},
{ attempts: 3, delay: 0, timeout: 1_000, retryIf: () => true },
)
expect(value).toBe("ready")
expect(failures).toHaveLength(5)
})
test("uses a caller-owned retry condition", async () => {
const failures: string[] = []
await expect(
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,6 +3,8 @@ export interface RetryOptions {
delay?: number
factor?: number
maxDelay?: number
/** Keep retrying, regardless of `attempts`, until the operation has run for at least this many milliseconds total. */
timeout?: number
retryIf?: (error: unknown) => boolean
}
Expand Down
Expand Up
@@ -35,17 +37,19 @@ export async function retry<T>(operation: () => Promise<T>, options: RetryOption
const delay = options.delay ?? 500
const factor = options.factor ?? 2
const maxDelay = options.maxDelay ?? 10_000
const timeout = options.timeout ?? 0
const retryIf = options.retryIf ?? isTransientError
let lastError: unknown
const startedAt = Date.now()
for (let attempt = 0; attempt < attempts ; attempt++) {
for (let attempt = 0; ; attempt++) {
try {
return await operation()
} catch (error) {
lastError = error
if (attempt === attempts - 1 || !retryIf(error)) throw error
await new Promise((resolve) => setTimeout(resolve, Math.min(delay * Math.pow(factor, attempt), maxDelay)))
const withinAttempts = attempt + 1 < attempts
const withinTimeout = Date.now() - startedAt < timeout
if (!retryIf(error) || (!withinAttempts && !withinTimeout)) throw error
const wait = Math.min(delay * Math.pow(factor, attempt), maxDelay)
await new Promise((resolve) => setTimeout(resolve, wait))
}
}
throw lastError
}
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.