feat(desktop): restart a stuck background service from the error page

This commit is contained in:
Filip Hejmowski
2026-10-19 18:37:09 +02:00
committed by Filip
Unverified
parent d0441c24b3
commit 546849c69f
10 changed files with 138 additions and 13 deletions
+4
View File
@@ -514,9 +514,13 @@ export const dict = {
"error.page.description": "An error occurred while loading the application.",
"error.page.description.status": "The server returned an HTTP {{status}} response.",
"error.page.description.localServerStartup": "An error occurred while starting the local server.",
"error.page.hint.restartService":
"Restarting the background service usually fixes this. Your sessions and history are kept.",
"error.page.details.label": "Error Details",
"error.page.action.restart": "Restart",
"error.page.action.reload": "Reload",
"error.page.action.restartService": "Restart Service",
"error.page.action.restartingService": "Restarting Service…",
"error.page.action.report": "Report Error",
"error.page.action.reported": "Error Reported",
"error.page.action.exportLogs": "Export Logs",
@@ -126,6 +126,9 @@ type PlatformBase = {
/** Write text to the native clipboard (desktop only) */
writeClipboardText?(text: string): Promise<void>
/** Stop the local background service and relaunch so a fresh one starts (desktop only) */
restartService?(): Promise<void>
/** Export collected diagnostic logs (desktop only) */
exportDebugLogs?(): Promise<string>
@@ -0,0 +1,65 @@
import { PlatformProvider, type Platform } from "@/runtime/platform/platform"
import { ErrorPage } from "./error"
const desktop = {
platform: "desktop",
os: "windows",
version: "2.0.32",
windowID: "story",
openExternal() {},
openDirectoryPickerDialog: async () => null,
restart: async () => {},
restartService: () => new Promise<void>(() => {}),
exportDebugLogs: async () => "",
notify: async () => {},
fetch: globalThis.fetch.bind(globalThis),
} satisfies Platform
function failure(message: string, frames: string[]) {
const error = new Error(message)
error.stack = [`Error: ${message}`, ...frames.map((frame) => ` at ${frame}`)].join("\n")
return error
}
function startupFailure() {
const error = failure("Background service failed to start", [
"fail (packages/client/src/service-probe.ts:30:45)",
"ensure (packages/client/src/promise/service.ts:74:41)",
])
Object.defineProperty(error, "localServerStartup", { value: true })
return error
}
const page = (platform: Platform, error: unknown) => (
<div class="flex h-screen w-full bg-background-base">
<PlatformProvider value={platform}>
<ErrorPage error={error} />
</PlatformProvider>
</div>
)
export default {
title: "App/Shell/Error Page",
id: "app-shell-error-page",
parameters: { layout: "fullscreen" },
}
export const LocalServerStartup = {
render: () => page(desktop, startupFailure()),
}
export const LocalServerStartupWithoutRestartService = {
render: () => page({ ...desktop, restartService: undefined }, startupFailure()),
}
export const UnexpectedError = {
render: () =>
page(
desktop,
failure("Cannot read properties of undefined (reading 'id')", [
"SessionRoute (packages/app/src/session/route.tsx:88:23)",
]),
),
}
+33 -1
View File
@@ -262,9 +262,11 @@ export const ErrorPage: Component<ErrorPageProps> = (props) => {
const [store, setStore] = createStore<{
actionError: string | undefined
captureException: typeof captureException | undefined
restartingService: boolean
}>({
actionError: undefined,
captureException: undefined,
restartingService: false,
})
function ensureFatalErrorRecorded() {
@@ -315,6 +317,19 @@ export const ErrorPage: Component<ErrorPageProps> = (props) => {
return state?.status === "ready" || state?.status === "download-required" ? state.version : undefined
}
// A service that failed to boot stays registered, so relaunching alone would reattach to it.
const restartService = () =>
errorDescriptionKey(props.error) === "error.page.description.localServerStartup"
? platform.restartService
: undefined
async function runRestartService(restart: () => Promise<void>) {
setStore({ restartingService: true, actionError: undefined })
await restart().catch((err) => {
setStore({ restartingService: false, actionError: formatError(err, language.t) })
})
}
async function exportDebugLogs() {
const exportLogs = platform.exportDebugLogs
@@ -343,6 +358,9 @@ export const ErrorPage: Component<ErrorPageProps> = (props) => {
? language.t("error.page.description.status", { status: status()! })
: language.t(errorDescriptionKey(props.error))}
</p>
<Show when={restartService()}>
<p class="text-sm text-text-weak max-w-md text-balance">{language.t("error.page.hint.restartService")}</p>
</Show>
</div>
<TextField
value={formattedError()}
@@ -353,7 +371,21 @@ export const ErrorPage: Component<ErrorPageProps> = (props) => {
label={language.t("error.page.details.label")}
hideLabel
/>
<div class="flex flex-row items-center justify-center gap-3 flex-wrap max-w-64">
<div class="flex flex-row items-center justify-center gap-3 flex-wrap max-w-lg">
<Show when={restartService()}>
{(restart) => (
<Button
size="large"
variant={store.restartingService ? "loading" : "contrast"}
disabled={store.restartingService}
onClick={() => void runRestartService(restart())}
>
{language.t(
store.restartingService ? "error.page.action.restartingService" : "error.page.action.restartService",
)}
</Button>
)}
</Show>
<Button size="large" onClick={platform.restart}>
{language.t(platform.platform === "web" ? "error.page.action.reload" : "error.page.action.restart")}
</Button>
@@ -71,6 +71,7 @@ export const appHandlers = AppRpcs.toLayer(
})
}),
AppRelaunch: () => Effect.sync(lifecycle.relaunch),
AppRestartService: () => background.stop.pipe(Effect.andThen(Effect.sync(lifecycle.relaunch))),
})
}),
)
@@ -15,6 +15,8 @@ const RegisteredService = Schema.Struct({ version: Schema.optional(Schema.String
export interface Interface {
readonly connection: Effect.Effect<SidecarCredentials.Data>
readonly reconnect: Effect.Effect<SidecarCredentials.Data>
/** Stops the registered service, including one stuck after a failed boot, so the next connect spawns a fresh one. */
readonly stop: Effect.Effect<void>
}
export class Service extends Context.Service<Service, Interface>()("opencode/desktop/BackgroundService") {}
@@ -24,12 +26,13 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const context = yield* Effect.context<FileSystem.FileSystem | Path.Path | DesktopCli.Service>()
return Service.of(
yield* BackgroundServiceState.make({
return Service.of({
...(yield* BackgroundServiceState.make({
initial: connect("initial").pipe(Effect.provide(context)),
reconnect: connect("reconnect").pipe(Effect.provide(context), Effect.orDie),
}),
)
})),
stop: stop().pipe(Effect.provide(context), Effect.orDie),
})
}),
)
@@ -46,14 +49,7 @@ const connect = Effect.fn("BackgroundService.connect")(function* (mode: "initial
if (isolated) process.env.XDG_STATE_HOME = app.getPath("userData")
const client = yield* Effect.promise(() => import("@opencode/client/service"))
const file =
process.env.OPENCODE_DESKTOP_SERVER_CHANNEL === "local"
? path.join(
process.env.XDG_STATE_HOME ?? path.join(app.getPath("home"), ".local", "state"),
"opencode",
"service-local.json",
)
: undefined
const file = registrationFile(path)
const ensure = (required = version) =>
client.Service.ensure({
@@ -120,6 +116,24 @@ const connect = Effect.fn("BackgroundService.connect")(function* (mode: "initial
return ready
})
const stop = Effect.fn("BackgroundService.stop")(function* () {
yield* Effect.logInfo("stopping v2 background service")
const path = yield* Path.Path
const client = yield* Effect.promise(() => import("@opencode/client/service"))
yield* Effect.tryPromise(() => client.Service.stop({ file: registrationFile(path) }))
})
function registrationFile(path: Path.Path) {
if (process.env.OPENCODE_DESKTOP_SERVER_CHANNEL !== "local") return undefined
return path.join(
process.env.XDG_STATE_HOME ?? path.join(app.getPath("home"), ".local", "state"),
"opencode",
"service-local.json",
)
}
function endpoint(url: string | undefined) {
if (!url || !URL.canParse(url)) return {}
const parsed = new URL(url)
@@ -57,6 +57,7 @@ export type ElectronAPI = {
setWindowFocus(): Promise<void>
showWindow(): Promise<void>
relaunch(): void
restartService(): Promise<void>
getZoomFactor(): Promise<number>
setZoomFactor(factor: number): Promise<void>
getPinchZoomEnabled(): Promise<boolean>
+1
View File
@@ -80,6 +80,7 @@ export const api: ElectronAPI = {
setWindowFocus: () => invoke("WindowSetFocus"),
showWindow: () => invoke("WindowShow"),
relaunch: () => send("AppRelaunch"),
restartService: () => invoke("AppRestartService"),
getZoomFactor: () => invoke("WindowGetZoomFactor"),
setZoomFactor: (factor) => invoke("WindowSetZoomFactor", { factor }),
getPinchZoomEnabled: () => invoke("WindowGetPinchZoomEnabled"),
@@ -28,6 +28,7 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind
setForceFocus: (enabled) => api.setForceFocus(enabled),
recordFatalRendererError: (error) => api.recordFatalRendererError(error),
restart: async () => api.relaunch(),
restartService: () => api.restartService(),
notify: createDesktopNotify(api),
fetch: (input, init) => {
if (input instanceof Request) return fetch(input)
@@ -66,6 +66,8 @@ export const AppSetNativeTranslations = Rpc.make("AppSetNativeTranslations", {
export const AppRelaunch = Rpc.make("AppRelaunch")
export const AppRestartService = Rpc.make("AppRestartService")
export const AppRpcs = RpcGroup.make(
AppAwaitInitialization,
AppReconnectService,
@@ -82,4 +84,5 @@ export const AppRpcs = RpcGroup.make(
AppRecordFatalRendererError,
AppSetNativeTranslations,
AppRelaunch,
AppRestartService,
)