fix(desktop): bound the renderer startup splash with an explicit state machine (#61798)

This commit is contained in:
Luke Parker
2026-11-04 16:25:02 -06:00
committed by GitHub
Unverified
parent 6000b7c51b
commit ce5c980f8b
7 changed files with 924 additions and 162 deletions
+165 -97
View File
@@ -13,18 +13,33 @@ import {
usePluginServers,
useTabs,
type LayoutRoute,
type Platform,
} from "@opencode/app/desktop"
import { useTheme } from "@opencode/ui/theme/context"
import type { BaseRouterProps } from "@solidjs/router"
import { createEffect, createMemo, createResource, createSignal, lazy, onCleanup, Show, Suspense } from "solid-js"
import { createStore } from "solid-js/store"
import type { ServerReadyData } from "../shared/ipc-contract"
import { createEffect, createMemo, createSignal, lazy, onCleanup, Show, Suspense, untrack } from "solid-js"
import type { ElectronAPI } from "./api-types"
import { DesktopFirstLaunchOnboarding } from "./onboarding"
import { createDesktopPlatform } from "./platform"
import { bindDesktopMenu } from "./platform/menu"
import { createSidecarResolver, initializationData, sidecarHttp } from "./startup/initialization"
import { createSidecarResolver, localServerStartupError, sidecarHttp } from "./startup/initialization"
import { preloadStoredLocale } from "./startup/locale"
import {
createStartupState,
selectDrawingPaused,
selectFirstLaunch,
selectFirstLaunchSplash,
selectInterfaceMounted,
selectOverlayFading,
selectOverlayMounted,
selectSidecar,
selectSplashDeep,
selectStartupFailure,
selectStartupLocale,
transitionStartup,
type StartupEffect,
type StartupEvent,
} from "./startup/machine"
import { LoadingSplash } from "./startup/splash"
import { getLastActiveUrl } from "./window/route-storage"
import { DesktopMemoryRouter } from "./window/router"
@@ -37,68 +52,33 @@ export function DesktopApp(props: { api: ElectronAPI; version: string }) {
const windowState = { id: props.api.getWindowID(), version: props.version }
const initialUrl = getLastActiveUrl(windowState.id)
const url = new URL(initialUrl, "http://localhost")
const route = currentRoute(url.pathname, url.search)
const [startup, setStartup] = createStore({
ready: false,
visible: true,
themeReady: false,
onboardingReady: false,
drawingReady: false,
route,
})
// The window was created with the answers the shell gate needs; only a fresh install, which has no
// onboarding decision yet, asks over IPC and waits for the port.
const bootstrap = props.api.getWindowBootstrap()
const [firstLaunch] = createResource(() =>
bootstrap.firstLaunchPending !== undefined
? Promise.resolve(bootstrap.firstLaunchPending)
: props.api.isFirstLaunchOnboardingPending().catch((error) => {
console.error("[desktop-onboarding] first launch check failed", error)
return false
}),
)
const platform = createDesktopPlatform(props.api, windowState)
const [sidecar] = createResource(() => props.api.awaitInitialization())
// The origin main moved every window to after initialization: this window's reconnect, another's, or a probed
// service that `Service.ensure` replaced.
const [movedSidecar, setMovedSidecar] = createSignal<ServerReadyData | undefined>(undefined, {
equals: (a, b) => a?.url === b?.url,
const startup = createStartupDriver({
api: props.api,
platform,
initialUrl,
route: currentRoute(url.pathname, url.search),
// The window was created with the answers the shell gate needs; only a fresh install, which has no
// onboarding decision yet, asks over IPC and waits for the port.
firstLaunch: props.api.getWindowBootstrap().firstLaunchPending,
})
onCleanup(props.api.onSidecarChanged((data) => setMovedSidecar(data)))
const [locale] = createResource(() => preloadStoredLocale(platform))
const [initialRoute] = createResource(
() => !firstLaunch.loading && (firstLaunch() && initialUrl === "/" ? "/new-session" : initialUrl),
preloadRoute,
)
const router = (routerProps: BaseRouterProps) => <DesktopMemoryRouter {...routerProps} windowID={windowState.id} />
const readyToReveal = () =>
startup.ready &&
(!import.meta.env.OPENCODE_TEST_ONBOARDING || !firstLaunch() || initialUrl !== "/" || startup.drawingReady)
// Reveal only after the theme and the first-launch splash choice are both resolved.
createEffect(() => {
if (!startup.themeReady || firstLaunch.loading) return
void props.api.themeReady()
})
function ReadyApp() {
function DesktopShell() {
const pluginServers = usePluginServers()
const ready = createMemo(() => !firstLaunch.loading && !sidecar.loading && !locale.loading && pluginServers.ready())
createEffect(() => {
if (pluginServers.ready()) startup.dispatch({ type: "plugin-servers.ready" })
})
// The shell only unmounts before the window when the error boundary above it catches an error.
onCleanup(() => startup.dispatch({ type: "boundary.tripped" }))
const activeSidecar = createMemo(
() => {
const data = movedSidecar() ?? initializationData(sidecar)
const data = selectSidecar(startup.state())
return data ? sidecarHttp(data) : undefined
},
@@ -115,8 +95,8 @@ export function DesktopApp(props: { api: ElectronAPI; version: string }) {
},
reconnect: createSidecarResolver({
api: props.api,
current: () => movedSidecar() ?? (sidecar.state === "ready" ? sidecar.latest : undefined),
update: (data) => setMovedSidecar(data),
current: () => selectSidecar(startup.state()),
update: (data) => startup.dispatch({ type: "sidecar.changed", data }),
}),
}
@@ -126,57 +106,61 @@ export function DesktopApp(props: { api: ElectronAPI; version: string }) {
])
return (
<Show when={ready()}>
<AppInterface servers={servers()} router={router}>
<DesktopStartupReady
routeReady={!initialRoute.loading && startup.onboardingReady}
onReady={() => setStartup("ready", true)}
onRoute={(route) => setStartup("route", route)}
/>
<DesktopFirstLaunchOnboarding
api={props.api}
initialUrl={initialUrl}
pending={firstLaunch() ?? false}
onReady={() => setStartup("onboardingReady", true)}
/>
<DesktopEffects api={props.api} />
<Suspense fallback={null}>
<Show when={activeSidecar()} keyed>
{(server) => <MigrationStatus server={server} />}
</Show>
</Suspense>
</AppInterface>
</Show>
<>
<Show when={selectStartupFailure(startup.state())} keyed>
{(failure) => {
throw failure.error
}}
</Show>
<Show when={selectInterfaceMounted(startup.state())}>
<AppInterface servers={servers()} router={router}>
<DesktopStartupReady dispatch={startup.dispatch} />
<DesktopFirstLaunchOnboarding
api={props.api}
initialUrl={initialUrl}
pending={selectFirstLaunch(startup.state())}
dispatch={startup.dispatch}
/>
<DesktopEffects api={props.api} />
<Suspense fallback={null}>
<Show when={activeSidecar()} keyed>
{(server) => <MigrationStatus server={server} />}
</Show>
</Suspense>
</AppInterface>
</Show>
</>
)
}
return (
<PlatformProvider value={platform}>
<AppBaseProviders
locale={locale.latest}
locale={selectStartupLocale(startup.state())}
onNativeTranslations={(bundle) => void props.api.setNativeTranslations(bundle).catch(() => undefined)}
onThemeApplied={(mode, scheme) => {
void props.api.setTitlebar({ mode, scheme })
setStartup("themeReady", true)
startup.dispatch({ type: "theme.applied" })
}}
>
<Show when={true}>{(_) => <ReadyApp />}</Show>
<Show when={!firstLaunch.loading && startup.visible}>
<DesktopShell />
<Show when={selectOverlayMounted(startup.state())}>
<div
data-component="startup-overlay"
class="fixed inset-0 z-[100] transition-opacity duration-300 ease-out"
classList={{ "pointer-events-none opacity-0": readyToReveal() }}
classList={{ "pointer-events-none opacity-0": selectOverlayFading(startup.state()) }}
onTransitionEnd={(event) => {
if (event.target !== event.currentTarget || !readyToReveal()) return
setStartup("visible", false)
if (event.target !== event.currentTarget) return
startup.dispatch({ type: "overlay.transition-ended" })
}}
>
<LoadingSplash
firstLaunch={!!firstLaunch() && initialUrl === "/"}
deep={startup.route.type === "draft"}
firstLaunch={selectFirstLaunchSplash(startup.state())}
deep={selectSplashDeep(startup.state())}
platform={platform}
preview={import.meta.env.OPENCODE_TEST_ONBOARDING}
onDrawEnd={() => setStartup("drawingReady", true)}
drawingPaused={selectDrawingPaused(startup.state())}
onDrawStart={() => startup.dispatch({ type: "drawing.started" })}
onDrawEnd={() => startup.dispatch({ type: "drawing.ended" })}
/>
</div>
</Show>
@@ -185,17 +169,101 @@ export function DesktopApp(props: { api: ElectronAPI; version: string }) {
)
}
function DesktopStartupReady(props: {
routeReady: boolean
onReady: () => void
onRoute: (route: LayoutRoute) => void
/** Runs the window's startup machine for the owner's lifetime: its requests to main, its preloads and its timer. */
function createStartupDriver(input: {
readonly api: ElectronAPI
readonly platform: Platform
readonly initialUrl: string
readonly route: LayoutRoute
readonly firstLaunch: boolean | undefined
}) {
const initial = createStartupState({
initialUrl: input.initialUrl,
route: input.route,
firstLaunch: input.firstLaunch,
preview: import.meta.env.OPENCODE_TEST_ONBOARDING,
reducedMotion: window.matchMedia("(prefers-reduced-motion: reduce)").matches,
})
const [state, setState] = createSignal(initial.state)
// The running phase timer; there is at most one.
const timers = new Set<ReturnType<typeof setTimeout>>()
// Events a transition's own state change raises (the app interface mounting) wait behind its effects.
const queue: StartupEvent[] = []
const drain = () => {
const event = queue[0]
if (!event) return
const next = transitionStartup(untrack(state), event)
setState(next.state)
next.effects.forEach(run)
queue.shift()
drain()
}
const dispatch = (event: StartupEvent) => {
queue.push(event)
if (queue.length === 1) drain()
}
const run = (effect: StartupEffect) => {
if (effect.type === "check-first-launch")
return void input.api.isFirstLaunchOnboardingPending().then(
(pending) => dispatch({ type: "first-launch.settled", pending }),
(error) => {
console.error("[desktop-onboarding] first launch check failed", error)
dispatch({ type: "first-launch.settled", pending: false })
},
)
// A failed locale preload falls back to English; the language provider still hydrates from the store.
if (effect.type === "preload-locale")
return void preloadStoredLocale(input.platform).then(
(locale) => dispatch({ type: "locale.settled", locale }),
() => dispatch({ type: "locale.settled", locale: undefined }),
)
if (effect.type === "await-sidecar")
return void input.api.awaitInitialization().then(
(data) => dispatch({ type: "sidecar.ready", data }),
(error) => dispatch({ type: "startup.failed", error: localServerStartupError(error) }),
)
// A route that fails to preload loads again when it renders.
if (effect.type === "preload-route")
return void preloadRoute(effect.url).then(
() => dispatch({ type: "route.preloaded" }),
() => dispatch({ type: "route.preloaded" }),
)
if (effect.type === "notify-theme-ready") return void input.api.themeReady().catch(() => undefined)
timers.forEach(clearTimeout)
timers.clear()
if (effect.type === "start-timer")
timers.add(setTimeout(() => dispatch({ type: `${effect.timer}.timed-out` }), effect.timeoutMs))
}
onCleanup(input.api.onSidecarChanged((data) => dispatch({ type: "sidecar.changed", data })))
onCleanup(() => dispatch({ type: "disposed" }))
initial.effects.forEach(run)
return { state, dispatch }
}
function DesktopStartupReady(props: { dispatch: (event: StartupEvent) => void }) {
const tabs = useTabs()
const route = useCurrentRoute()
createEffect(() => props.onRoute(route()))
createEffect(() => props.dispatch({ type: "route.changed", route: route() }))
createEffect(() => {
if (!props.routeReady || !tabs.ready() || !tabs.infoReady()) return
props.onReady()
if (!tabs.ready() || !tabs.infoReady()) return
props.dispatch({ type: "tabs.ready" })
})
return null
@@ -1,67 +1,64 @@
import { ServerConnection, useCurrentRoute, useGlobal, useServers, useTabs } from "@opencode/app/desktop"
import { createResource } from "solid-js"
import { onMount } from "solid-js"
import type { ElectronAPI } from "../api-types"
import type { StartupEvent } from "../startup/machine"
export function DesktopFirstLaunchOnboarding(props: {
api: ElectronAPI
initialUrl: string
pending: boolean
onReady: () => void
dispatch: (event: StartupEvent) => void
}) {
const server = useServers()
const global = useGlobal()
const tabs = useTabs()
const route = useCurrentRoute()
const [completed] = createResource(async () => {
await runFirstLaunchOnboarding()
return null
// Startup reports the result: a failure reaches the app's recovery screen.
onMount(() => {
if (!props.pending) return
void runFirstLaunchOnboarding().then(
() => props.dispatch({ type: "onboarding.settled" }),
(error) => props.dispatch({ type: "startup.failed", error }),
)
})
async function runFirstLaunchOnboarding() {
try {
if (!props.pending) return
await Promise.all([tabs.ready.promise, tabs.recentReady.promise].map((p) => p ?? Promise.resolve()))
await Promise.all([tabs.ready.promise, tabs.recentReady.promise].map((p) => p ?? Promise.resolve()))
const shouldTrigger =
props.initialUrl === "/" &&
route().type === "home" &&
tabs.store.length === 0 &&
server.list.every(ServerConnection.builtin)
const shouldTrigger =
props.initialUrl === "/" &&
route().type === "home" &&
tabs.store.length === 0 &&
server.list.every(ServerConnection.builtin)
console.info("[desktop-onboarding] first launch onboarding evaluated", {
pending: props.pending,
shouldTrigger,
initialUrl: props.initialUrl,
tabs: tabs.store.length,
servers: server.list.map(ServerConnection.key),
})
console.info("[desktop-onboarding] first launch onboarding evaluated", {
pending: props.pending,
shouldTrigger,
initialUrl: props.initialUrl,
tabs: tabs.store.length,
servers: server.list.map(ServerConnection.key),
})
const directory = await props.api.finishFirstLaunchOnboarding(shouldTrigger)
const directory = await props.api.finishFirstLaunchOnboarding(shouldTrigger)
if (!shouldTrigger || !directory) return
if (!shouldTrigger || !directory) return
console.info("[desktop-onboarding] starting first launch draft", { directory })
const sidecar = ServerConnection.Key.make("sidecar")
const ctx = global.serverCtx(sidecar)
console.info("[desktop-onboarding] starting first launch draft", { directory })
const sidecar = ServerConnection.Key.make("sidecar")
const ctx = global.serverCtx(sidecar)
if (ctx) {
// Load the initial provider/model state before the draft transition exposes the composer.
await Promise.all([
ctx.projects.add(directory),
ctx.data.location.provider.sync({ directory }),
ctx.data.location.model.sync({ directory }),
])
}
tabs.select(await tabs.newDraft({ server: sidecar, directory }))
} finally {
props.onReady()
if (ctx) {
// Load the initial provider/model state before the draft transition exposes the composer.
await Promise.all([
ctx.projects.add(directory),
ctx.data.location.provider.sync({ directory }),
ctx.data.location.model.sync({ directory }),
])
}
tabs.select(await tabs.newDraft({ server: sidecar, directory }))
}
// Let startup failures reach the app's recovery screen, including its splash boundary.
return <>{completed()}</>
return null
}
@@ -1,28 +1,18 @@
import { describe, expect, test } from "bun:test"
import { createSidecarResolver, initializationData } from "./initialization"
function failure(error: Error | string) {
try {
initializationData(Object.assign(() => undefined, { error }))
} catch (caught) {
return caught
}
}
import { createSidecarResolver, localServerStartupError } from "./initialization"
describe("desktop renderer initialization", () => {
test("throws the original initialization error, marked as a local server startup, before rendering", () => {
test("keeps the original initialization error, marked as a local server startup", () => {
const error = new Error("Cannot migrate session_message projections")
expect(failure(error)).toBe(error)
expect(localServerStartupError(error)).toBe(error)
expect(error).toHaveProperty("localServerStartup", true)
// The RPC error text reaches the error screen unchanged.
expect(error.message).toBe("Cannot migrate session_message projections")
// A falsy error is still an error.
const empty = failure("")
const empty = localServerStartupError("")
expect(empty).toBeInstanceOf(Error)
expect(empty).toHaveProperty("message", "")
expect(empty).toHaveProperty("localServerStartup", true)
const sidecar = { url: "http://127.0.0.1:1234" }
expect(initializationData(Object.assign(() => sidecar, { error: undefined }))).toBe(sidecar)
})
test("refreshes the managed sidecar endpoint", async () => {
@@ -2,12 +2,12 @@ import type { ElectronAPI } from "../api-types"
type SidecarData = Awaited<ReturnType<ElectronAPI["awaitInitialization"]>>
export function initializationData<A>(state: (() => A | undefined) & { error: unknown }) {
if (state.error === undefined) return state()
const failure = state.error instanceof Error ? state.error : new Error(String(state.error))
/** Marks a startup failure so the error page describes it as the local server failing to start. */
export function localServerStartupError(cause: unknown) {
const failure = cause instanceof Error ? cause : new Error(String(cause))
Object.defineProperty(failure, "localServerStartup", { value: true })
throw failure
return failure
}
// The main process adds Authorization to sidecar requests (`wireRendererHeaders`); the renderer never
@@ -0,0 +1,264 @@
import { describe, expect, test } from "bun:test"
import {
createStartupState,
FADE_TIMEOUT_MS,
HYDRATION_TIMEOUT_MS,
selectDrawingPaused,
selectFirstLaunch,
selectInterfaceMounted,
selectOverlayMounted,
selectSidecar,
selectStartupFailure,
selectStartupLocale,
transitionStartup,
type StartupEffect,
type StartupEvent,
type StartupState,
} from "./machine"
const sidecar = { url: "http://127.0.0.1:4096" }
const moved = { url: "http://127.0.0.1:5096" }
function start(input: { firstLaunch?: boolean; preview?: boolean; reducedMotion?: boolean; initialUrl?: string } = {}) {
return createStartupState({
initialUrl: input.initialUrl ?? "/",
route: { type: "home" },
firstLaunch: "firstLaunch" in input ? input.firstLaunch : false,
preview: input.preview ?? false,
reducedMotion: input.reducedMotion ?? false,
})
}
// Folds events through the machine and keeps the effects of each step.
function replay(events: readonly StartupEvent[], from: StartupState = start().state) {
return events.reduce<{ state: StartupState; effects: (readonly StartupEffect[])[] }>(
(result, event) => {
const next = transitionStartup(result.state, event)
return { state: next.state, effects: [...result.effects, next.effects] }
},
{ state: from, effects: [] },
)
}
const notify: StartupEffect = { type: "notify-theme-ready" }
const cancel: StartupEffect = { type: "cancel-timer" }
const hydration: StartupEffect[] = [
cancel,
{ type: "start-timer", timer: "hydration", timeoutMs: HYDRATION_TIMEOUT_MS },
]
const fade: StartupEffect[] = [cancel, { type: "start-timer", timer: "fade", timeoutMs: FADE_TIMEOUT_MS }]
// Everything a returning launch waits for before the app interface mounts.
const mounted: StartupEvent[] = [
{ type: "theme.applied" },
{ type: "locale.settled", locale: "de" },
{ type: "plugin-servers.ready" },
{ type: "route.preloaded" },
{ type: "sidecar.ready", data: sidecar },
]
describe("desktop startup", () => {
test("shows the error page when the local server never answers", () => {
const result = replay([
{ type: "theme.applied" },
{ type: "sidecar.timed-out" },
{ type: "sidecar.ready", data: sidecar },
])
expect(result.state.status).toBe("failed")
expect(selectStartupFailure(result.state)?.error).toHaveProperty("localServerStartup", true)
expect(selectOverlayMounted(result.state)).toBe(false)
expect(result.effects).toEqual([[notify], [cancel], []])
})
test("shows the window with the error page when a fresh install never learns whether to onboard", () => {
const result = replay(
[{ type: "theme.applied" }, { type: "sidecar.timed-out" }, { type: "first-launch.settled", pending: true }],
start({ firstLaunch: undefined }).state,
)
expect(start({ firstLaunch: undefined }).effects[0]).toEqual({ type: "check-first-launch" })
expect(result.state.status).toBe("failed")
// Nothing was shown before: neither the splash nor the window.
expect(result.effects).toEqual([[], [notify, cancel], []])
})
test.each([
["plugin servers", mounted.filter((event) => event.type !== "plugin-servers.ready"), "booting"],
["the locale", mounted.filter((event) => event.type !== "locale.settled"), "booting"],
["the route", mounted.filter((event) => event.type !== "route.preloaded"), "hydrating"],
["tabs", mounted, "hydrating"],
] satisfies [string, StartupEvent[], string][])(
"shows the app with the server it has when %s never settle",
(_name, events, waiting) => {
const before = replay(events)
const result = replay([{ type: "hydration.timed-out" }], before.state)
expect(before.state.status).toBe(waiting)
expect(result.state.status).toBe("fading")
expect(selectInterfaceMounted(result.state)).toBe(true)
expect(selectSidecar(result.state)).toBe(sidecar)
expect(result.effects).toEqual([fade])
},
)
test("shows the app when onboarding or the preview wordmark never finishes", () => {
const preview = start({ firstLaunch: true, preview: true })
const result = replay([...mounted, { type: "tabs.ready" }, { type: "hydration.timed-out" }], preview.state)
expect(result.state.status).toBe("fading")
expect(selectFirstLaunch(result.state)).toBe(true)
})
test("removes the overlay when its transition never ends", () => {
const fading = replay([...mounted, { type: "tabs.ready" }])
const result = replay([{ type: "fade.timed-out" }, { type: "overlay.transition-ended" }], fading.state)
expect(fading.state.status).toBe("fading")
expect(fading.effects.at(-1)).toEqual(fade)
expect(result.state.status).toBe("revealed")
expect(selectOverlayMounted(result.state)).toBe(false)
expect(result.effects).toEqual([[cancel], []])
})
test("skips the fade under reduced motion", () => {
const result = replay([...mounted, { type: "tabs.ready" }], start({ reducedMotion: true }).state)
expect(result.state.status).toBe("revealed")
expect(result.effects.at(-1)).toEqual([cancel])
})
test("ignores the wordmark animation outside the onboarding preview", () => {
const booting = start({ firstLaunch: true }).state
const result = transitionStartup(booting, { type: "drawing.ended" })
expect(result.state).toBe(booting)
expect(result.effects).toEqual([])
})
test("waits for the preview wordmark to draw once the window is focused", () => {
const preview = start({ firstLaunch: true, preview: true }).state
const ready = replay([...mounted, { type: "onboarding.settled" }, { type: "tabs.ready" }], preview)
expect(selectDrawingPaused(preview)).toBe(true)
expect(ready.state.status).toBe("hydrating")
const drawn = replay(
[{ type: "drawing.ended" }, { type: "drawing.started" }, { type: "drawing.ended" }],
ready.state,
)
expect(drawn.effects).toEqual([[], [], fade])
expect(drawn.state.status).toBe("fading")
})
test("falls back to English when the stored locale fails to load", () => {
const result = replay(
mounted.map((event) => (event.type === "locale.settled" ? { ...event, locale: undefined } : event)),
)
expect(result.state.status).toBe("hydrating")
expect(selectStartupLocale(result.state)).toBeUndefined()
expect(selectStartupLocale(replay(mounted).state)).toBe("de")
})
test("onboards a fresh install on the new-session route", () => {
const fresh = start({ firstLaunch: undefined })
const result = replay(
[
{ type: "theme.applied" },
{ type: "first-launch.settled", pending: true },
...mounted.slice(1),
{ type: "tabs.ready" },
{ type: "onboarding.settled" },
{ type: "overlay.transition-ended" },
],
fresh.state,
)
expect(fresh.effects).toEqual([
{ type: "check-first-launch" },
{ type: "preload-locale" },
{ type: "await-sidecar" },
{ type: "start-timer", timer: "sidecar", timeoutMs: 300_000 },
])
expect(result.effects).toEqual([
[],
[{ type: "preload-route", url: "/new-session" }, notify],
[],
[],
[],
hydration,
[],
fade,
[cancel],
])
expect(result.state.status).toBe("revealed")
})
test("follows a sidecar that moves before or after the window's own answer", () => {
const early = replay([{ type: "sidecar.changed", data: moved }, ...mounted])
const late = replay([...mounted, { type: "tabs.ready" }, { type: "sidecar.changed", data: moved }])
expect(selectSidecar(early.state)).toBe(moved)
expect(late.state.status).toBe("fading")
expect(selectSidecar(late.state)).toBe(moved)
})
test.each([
["the local server fails", [], "booting"],
["onboarding fails", mounted, "hydrating"],
[
"onboarding fails after the app shows",
[...mounted, { type: "tabs.ready" }, { type: "fade.timed-out" }],
"revealed",
],
] satisfies [string, StartupEvent[], string][])("shows the error page when %s", (_name, events, from) => {
const error = new Error("boom")
const before = replay(events)
const result = transitionStartup(before.state, { type: "startup.failed", error })
expect(before.state.status).toBe(from)
expect(selectStartupFailure(result.state)).toEqual({ error })
expect(selectInterfaceMounted(result.state)).toBe(false)
})
test("stops its timer when the error boundary catches a render error", () => {
const fresh = replay(
[{ type: "theme.applied" }, { type: "boundary.tripped" }],
start({ firstLaunch: undefined }).state,
)
expect(fresh.state.status).toBe("failed")
expect(selectStartupFailure(fresh.state)).toBeUndefined()
expect(fresh.effects).toEqual([[], [notify, cancel]])
})
test("ignores timers from a phase it has left", () => {
const hydrating = replay(mounted).state
const fading = replay([{ type: "tabs.ready" }], hydrating).state
expect(transitionStartup(hydrating, { type: "sidecar.timed-out" }).state).toBe(hydrating)
expect(transitionStartup(hydrating, { type: "fade.timed-out" }).state).toBe(hydrating)
expect(transitionStartup(fading, { type: "hydration.timed-out" }).state).toBe(fading)
})
test("cancels its timer on dispose and ignores everything after", () => {
const disposed = replay([{ type: "sidecar.ready", data: sidecar }, { type: "disposed" }])
const after = replay(
[...mounted, { type: "hydration.timed-out" }, { type: "startup.failed", error: 1 }],
disposed.state,
)
expect(disposed.effects.at(-1)).toEqual([cancel])
expect(after.state).toBe(disposed.state)
expect(after.effects.flat()).toEqual([])
})
})
@@ -0,0 +1,444 @@
import type { LayoutRoute, Locale } from "@opencode/app/desktop"
import type { ServerReadyData } from "../../shared/ipc-contract"
import { localServerStartupError } from "./initialization"
/**
* How long the window waits for the local server before it shows the error page. Main bounds its own start (two
* 120 s attempts at most), so this only catches a renderer that never hears back, such as a lost IPC port.
*/
export const SIDECAR_TIMEOUT_MS = 300_000
/** How long the window waits, once the server is known, for the rest of startup before it shows the app anyway. */
export const HYDRATION_TIMEOUT_MS = 30_000
/** Fallback for the 300 ms opacity transition on `startup-overlay`. */
export const FADE_TIMEOUT_MS = 350
export type StartupTimer = "sidecar" | "hydration" | "fade"
export type LocaleGate = { readonly settled: false } | { readonly settled: true; readonly value: Locale | undefined }
/** Only the first-launch onboarding preview (`OPENCODE_TEST_ONBOARDING` on `/`) waits for the wordmark to draw. */
export type DrawingPhase = "not-needed" | "pending" | "running" | "done"
/**
* The window's startup splash, from the first render to the revealed app. The app interface mounts once the server,
* the first-launch decision, the locale and the plugin servers are known (`hydrating`); the splash fades out once the
* route, onboarding and tabs are ready. Every waiting phase has a timer, so the splash cannot stay up forever.
*/
export type StartupState =
| {
readonly status: "booting"
readonly initialUrl: string
readonly preview: boolean
readonly reducedMotion: boolean
readonly route: LayoutRoute
/** `undefined` until a fresh install has asked main whether onboarding is pending. */
readonly firstLaunch: boolean | undefined
readonly locale: LocaleGate
readonly themeApplied: boolean
readonly sidecar: ServerReadyData | undefined
readonly pluginServersReady: boolean
readonly routePreloaded: boolean
readonly drawing: DrawingPhase
}
| {
readonly status: "hydrating"
readonly initialUrl: string
readonly reducedMotion: boolean
readonly route: LayoutRoute
readonly firstLaunch: boolean
readonly locale: LocaleGate
readonly themeApplied: boolean
readonly sidecar: ServerReadyData
readonly routePreloaded: boolean
readonly onboardingDone: boolean
readonly tabsReady: boolean
readonly drawing: DrawingPhase
}
| {
readonly status: "fading"
readonly initialUrl: string
readonly route: LayoutRoute
readonly firstLaunch: boolean
readonly locale: LocaleGate
readonly themeApplied: boolean
readonly sidecar: ServerReadyData
}
| {
readonly status: "revealed"
readonly firstLaunch: boolean
readonly locale: LocaleGate
readonly themeApplied: boolean
readonly sidecar: ServerReadyData
}
| {
readonly status: "failed"
/** `undefined` when the error boundary already caught the error itself. */
readonly failure: { readonly error: unknown } | undefined
readonly locale: LocaleGate
readonly themeApplied: boolean
}
| { readonly status: "disposed" }
export type StartupEvent =
| { readonly type: "theme.applied" }
| { readonly type: "first-launch.settled"; readonly pending: boolean }
| { readonly type: "locale.settled"; readonly locale: Locale | undefined }
| { readonly type: "sidecar.ready"; readonly data: ServerReadyData }
| { readonly type: "sidecar.changed"; readonly data: ServerReadyData }
| { readonly type: "plugin-servers.ready" }
| { readonly type: "route.preloaded" }
| { readonly type: "route.changed"; readonly route: LayoutRoute }
| { readonly type: "onboarding.settled" }
| { readonly type: "tabs.ready" }
| { readonly type: "drawing.started" }
| { readonly type: "drawing.ended" }
| { readonly type: "overlay.transition-ended" }
| { readonly type: "sidecar.timed-out" }
| { readonly type: "hydration.timed-out" }
| { readonly type: "fade.timed-out" }
| { readonly type: "startup.failed"; readonly error: unknown }
| { readonly type: "boundary.tripped" }
| { readonly type: "disposed" }
export type StartupEffect =
| { readonly type: "check-first-launch" }
| { readonly type: "preload-locale" }
| { readonly type: "await-sidecar" }
| { readonly type: "preload-route"; readonly url: string }
| { readonly type: "notify-theme-ready" }
| { readonly type: "start-timer"; readonly timer: StartupTimer; readonly timeoutMs: number }
| { readonly type: "cancel-timer" }
export type StartupTransition = {
readonly state: StartupState
readonly effects: readonly StartupEffect[]
}
const DISPOSED: StartupState = Object.freeze({ status: "disposed" })
const UNSETTLED: LocaleGate = Object.freeze({ settled: false })
const TIMEOUTS: Record<StartupTimer, number> = {
sidecar: SIDECAR_TIMEOUT_MS,
hydration: HYDRATION_TIMEOUT_MS,
fade: FADE_TIMEOUT_MS,
}
export function createStartupState(input: {
readonly initialUrl: string
readonly route: LayoutRoute
/** Known from the window bootstrap, except on a fresh install. */
readonly firstLaunch: boolean | undefined
readonly preview: boolean
readonly reducedMotion: boolean
}): StartupTransition {
const state: StartupState = {
status: "booting",
initialUrl: input.initialUrl,
preview: input.preview,
reducedMotion: input.reducedMotion,
route: input.route,
firstLaunch: input.firstLaunch,
locale: UNSETTLED,
themeApplied: false,
sidecar: undefined,
pluginServersReady: false,
routePreloaded: false,
drawing: drawingPhase(input.preview, input.firstLaunch, input.initialUrl),
}
return {
state,
effects: [
input.firstLaunch === undefined
? { type: "check-first-launch" }
: { type: "preload-route", url: preloadTarget(input.initialUrl, input.firstLaunch) },
{ type: "preload-locale" },
{ type: "await-sidecar" },
{ type: "start-timer", timer: "sidecar", timeoutMs: SIDECAR_TIMEOUT_MS },
],
}
}
export function transitionStartup(state: StartupState, event: StartupEvent): StartupTransition {
const next = step(state, event)
if (next.state === state) return next
// The theme notification and the phase timer follow from the state itself, so every path keeps them in step.
const timer = activeTimer(next.state)
return {
state: next.state,
effects: [
...next.effects,
...(themeNotified(state) || !themeNotified(next.state) ? [] : [{ type: "notify-theme-ready" } as const]),
...(timer === activeTimer(state)
? []
: [
{ type: "cancel-timer" } as const,
...(timer ? [{ type: "start-timer", timer, timeoutMs: TIMEOUTS[timer] } as const] : []),
]),
],
}
}
function step(state: StartupState, event: StartupEvent): StartupTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") return to(DISPOSED)
if (event.type === "theme.applied")
return state.themeApplied ? unchanged(state) : to({ ...state, themeApplied: true })
if (event.type === "locale.settled") {
if (state.locale.settled) return unchanged(state)
const locale = { settled: true, value: event.locale } as const
return state.status === "booting" ? mount({ ...state, locale }) : to({ ...state, locale })
}
if (state.status === "failed") return unchanged(state)
if (event.type === "startup.failed") return fail(state, { error: event.error })
if (event.type === "sidecar.changed") {
if (state.sidecar?.url === event.data.url) return unchanged(state)
return state.status === "booting" ? mount({ ...state, sidecar: event.data }) : to({ ...state, sidecar: event.data })
}
if (state.status === "revealed") return unchanged(state)
if (event.type === "boundary.tripped") return fail(state, undefined)
if (state.status === "fading") {
if (event.type === "overlay.transition-ended" || event.type === "fade.timed-out")
return to({
status: "revealed",
firstLaunch: state.firstLaunch,
locale: state.locale,
themeApplied: state.themeApplied,
sidecar: state.sidecar,
})
if (event.type === "route.changed" && event.route !== state.route) return to({ ...state, route: event.route })
return unchanged(state)
}
if (event.type === "drawing.started")
return state.drawing === "pending" ? to({ ...state, drawing: "running" }) : unchanged(state)
if (event.type === "drawing.ended") {
if (state.drawing !== "running") return unchanged(state)
return state.status === "booting" ? to({ ...state, drawing: "done" }) : reveal({ ...state, drawing: "done" })
}
if (event.type === "route.preloaded") {
if (state.routePreloaded) return unchanged(state)
return state.status === "booting"
? to({ ...state, routePreloaded: true })
: reveal({ ...state, routePreloaded: true })
}
if (state.status === "booting") return boot(state, event)
if (event.type === "route.changed")
return event.route === state.route ? unchanged(state) : to({ ...state, route: event.route })
if (event.type === "onboarding.settled")
return state.onboardingDone ? unchanged(state) : reveal({ ...state, onboardingDone: true })
if (event.type === "tabs.ready") return state.tabsReady ? unchanged(state) : reveal({ ...state, tabsReady: true })
if (event.type === "hydration.timed-out") return beginReveal(state)
return unchanged(state)
}
function boot(state: Extract<StartupState, { status: "booting" }>, event: StartupEvent): StartupTransition {
if (event.type === "first-launch.settled") {
if (state.firstLaunch !== undefined) return unchanged(state)
const next = mount({
...state,
firstLaunch: event.pending,
drawing: drawingPhase(state.preview, event.pending, state.initialUrl),
})
return {
state: next.state,
effects: [{ type: "preload-route", url: preloadTarget(state.initialUrl, event.pending) }, ...next.effects],
}
}
// A sidecar that moved before this window's own answer arrived is the newer one.
if (event.type === "sidecar.ready") return state.sidecar ? unchanged(state) : mount({ ...state, sidecar: event.data })
if (event.type === "plugin-servers.ready")
return state.pluginServersReady ? unchanged(state) : mount({ ...state, pluginServersReady: true })
if (event.type === "sidecar.timed-out" && !state.sidecar)
return fail(state, {
error: localServerStartupError(new Error("Timed out waiting for local server initialization")),
})
// The server is up, so show the app with whatever else is still loading rather than the splash.
if (event.type === "hydration.timed-out" && state.sidecar)
return beginReveal({ ...state, sidecar: state.sidecar, firstLaunch: state.firstLaunch ?? false })
return unchanged(state)
}
function mount(state: Extract<StartupState, { status: "booting" }>): StartupTransition {
if (!state.sidecar || state.firstLaunch === undefined || !state.locale.settled || !state.pluginServersReady)
return to(state)
return to({
status: "hydrating",
initialUrl: state.initialUrl,
reducedMotion: state.reducedMotion,
route: state.route,
firstLaunch: state.firstLaunch,
locale: state.locale,
themeApplied: state.themeApplied,
sidecar: state.sidecar,
routePreloaded: state.routePreloaded,
onboardingDone: !state.firstLaunch,
tabsReady: false,
drawing: state.drawing,
})
}
function reveal(state: Extract<StartupState, { status: "hydrating" }>): StartupTransition {
const drawn = state.drawing === "not-needed" || state.drawing === "done"
if (!state.routePreloaded || !state.onboardingDone || !state.tabsReady || !drawn) return to(state)
return beginReveal(state)
}
function beginReveal(state: {
readonly initialUrl: string
readonly reducedMotion: boolean
readonly route: LayoutRoute
readonly firstLaunch: boolean
readonly locale: LocaleGate
readonly themeApplied: boolean
readonly sidecar: ServerReadyData
}): StartupTransition {
// Under reduced motion the overlay has no transition to wait for.
if (state.reducedMotion)
return to({
status: "revealed",
firstLaunch: state.firstLaunch,
locale: state.locale,
themeApplied: state.themeApplied,
sidecar: state.sidecar,
})
return to({
status: "fading",
initialUrl: state.initialUrl,
route: state.route,
firstLaunch: state.firstLaunch,
locale: state.locale,
themeApplied: state.themeApplied,
sidecar: state.sidecar,
})
}
function fail(
state: { readonly locale: LocaleGate; readonly themeApplied: boolean },
failure: { readonly error: unknown } | undefined,
): StartupTransition {
return to({ status: "failed", failure, locale: state.locale, themeApplied: state.themeApplied })
}
function to(state: StartupState): StartupTransition {
return { state, effects: [] }
}
function unchanged(state: StartupState): StartupTransition {
return { state, effects: [] }
}
/** Main shows the window once the theme is applied and, before the app mounts, the splash is chosen. */
function themeNotified(state: StartupState) {
if (state.status === "disposed" || !state.themeApplied) return false
return state.status !== "booting" || state.firstLaunch !== undefined
}
function activeTimer(state: StartupState): StartupTimer | undefined {
if (state.status === "booting") return state.sidecar ? "hydration" : "sidecar"
if (state.status === "hydrating") return "hydration"
if (state.status === "fading") return "fade"
}
function drawingPhase(preview: boolean, firstLaunch: boolean | undefined, initialUrl: string): DrawingPhase {
return preview && firstLaunch === true && initialUrl === "/" ? "pending" : "not-needed"
}
function preloadTarget(initialUrl: string, firstLaunch: boolean) {
return firstLaunch && initialUrl === "/" ? "/new-session" : initialUrl
}
/** The locale the language provider starts with; it never suspends or throws. */
export function selectStartupLocale(state: StartupState) {
if (state.status === "disposed" || !state.locale.settled) return undefined
return state.locale.value
}
/** The startup error to throw inside the app's error boundary. */
export function selectStartupFailure(state: StartupState) {
return state.status === "failed" ? state.failure : undefined
}
export function selectInterfaceMounted(state: StartupState) {
return state.status === "hydrating" || state.status === "fading" || state.status === "revealed"
}
export function selectSidecar(state: StartupState) {
return state.status === "failed" || state.status === "disposed" ? undefined : state.sidecar
}
/** Whether this window runs first-launch onboarding, read once when the app interface mounts. */
export function selectFirstLaunch(state: StartupState) {
return (state.status === "hydrating" || state.status === "fading" || state.status === "revealed") && state.firstLaunch
}
export function selectOverlayMounted(state: StartupState) {
if (state.status === "booting") return state.firstLaunch !== undefined
return state.status === "hydrating" || state.status === "fading"
}
export function selectOverlayFading(state: StartupState) {
return state.status === "fading"
}
export function selectFirstLaunchSplash(state: StartupState) {
if (state.status !== "booting" && state.status !== "hydrating" && state.status !== "fading") return false
return state.firstLaunch === true && state.initialUrl === "/"
}
export function selectSplashDeep(state: StartupState) {
if (state.status !== "booting" && state.status !== "hydrating" && state.status !== "fading") return false
return state.route.type === "draft"
}
/** The first-launch wordmark waits for a visible, focused window before it draws. */
export function selectDrawingPaused(state: StartupState) {
return (state.status === "booting" || state.status === "hydrating") && state.drawing === "pending"
}
@@ -2,24 +2,23 @@ import { Splash } from "@opencode/ui/logo"
import { Wordmark } from "@opencode/ui/wordmark"
import type { Platform } from "@opencode/app/desktop"
import { onCleanup, onMount, Show } from "solid-js"
import { createStore } from "solid-js/store"
import "./splash.css"
export function LoadingSplash(props: {
deep: boolean
firstLaunch: boolean
platform: Platform
preview: boolean
drawingPaused: boolean
onDrawStart: () => void
onDrawEnd: () => void
}) {
const [drawing, setDrawing] = createStore({ started: false })
onMount(() => {
if (!props.preview || !props.firstLaunch) return
if (!props.drawingPaused) return
const motion = window.matchMedia("(prefers-reduced-motion: reduce)")
const start = () => {
if (document.visibilityState !== "visible" || !document.hasFocus()) return
setDrawing("started", true)
props.onDrawStart()
if (motion.matches) props.onDrawEnd()
}
@@ -64,7 +63,7 @@ export function LoadingSplash(props: {
>
<div
data-component="first-launch-splash"
data-drawing={props.preview && !drawing.started ? "pending" : "running"}
data-drawing={props.drawingPaused ? "pending" : "running"}
aria-hidden="true"
class="h-dvh w-screen bg-v2-background-bg-base"
style={{