diff --git a/packages/desktop/src/main/windows/index.ts b/packages/desktop/src/main/windows/index.ts index bcb5298a1c9..df825fb50bd 100644 --- a/packages/desktop/src/main/windows/index.ts +++ b/packages/desktop/src/main/windows/index.ts @@ -28,11 +28,12 @@ import { registerRendererProtocol, setProtocolReporter } from "./protocol" import { loadWindow } from "./scheme" import { createWindowRegistry } from "./registry" import { windowRecovery } from "./recovery" +import { createRevealDriver } from "./reveal-machine" import { takeEarlyWindow, type EarlyWindow } from "./early" import { manageWindowState, readWindowState, resolveWindowState, windowStateFile } from "./window-state" import { allowRendererPermissions, wireNavigationPolicy, wireRendererHeaders } from "./security" -const themeReady = new WeakMap void>() +const revealDrivers = new WeakMap>() const displays = { all: () => screen.getAllDisplays().map((display) => display.bounds), @@ -120,7 +121,7 @@ export function onMainWindow(listener: (win: BrowserWindow, id: string) => void) } export function setWindowThemeReady(win: BrowserWindow) { - themeReady.get(win)?.() + revealDrivers.get(win)?.dispatch({ type: "theme.ready" }) } export const mainWindows = Effect.fn("Window.make")(function* () { @@ -176,17 +177,6 @@ export const mainWindows = Effect.fn("Window.make")(function* () { manageWindowState(win, stateFile, state, displays) } - wireWindowRecovery(win, id, () => relaunchHandler()) - register(win, id) - wireFullscreen(win) - wireFocus(win) - - if (!early) loadWindow(win, "index.html") - wireZoom(win) - let contentReady = false - let appliedTheme = false - let revealed = !!early - const focusForTests = () => { if (app.isPackaged || process.env.OPENCODE_TEST_ONBOARDING !== "1") return @@ -194,32 +184,43 @@ export const mainWindows = Effect.fn("Window.make")(function* () { win.focus() } + const reveal = createRevealDriver({ + early: !!early, + show: (reason) => { + if (win.isDestroyed()) return + win.show() + focusForTests() + runFork(Effect.logInfo("main window visible", reason === "ready" ? { window: id } : { window: id, reason })) + }, + }) + + revealDrivers.set(win, reveal) + + wireWindowRecovery(win, id, { + relaunch: () => relaunchHandler(), + reveal: () => reveal.dispatch({ type: "recovery.requested" }), + }) + register(win, id) + wireFullscreen(win) + wireFocus(win) + + if (!early) loadWindow(win, "index.html") + wireZoom(win) + if (early) { focusForTests() runFork(Effect.logInfo("main window visible", { window: id, shownAt: early.shownAt })) } - const reveal = () => { - if (!contentReady || !appliedTheme || revealed || win.isDestroyed()) return - revealed = true - win.show() - focusForTests() - runFork(Effect.logInfo("main window visible", { window: id })) - } + const contentReady = () => reveal.dispatch({ type: "content.ready" }) - const ready = () => { - contentReady = true - reveal() - } + win.once("ready-to-show", contentReady) - themeReady.set(win, () => { - appliedTheme = true - reveal() + if (process.platform === "linux") win.webContents.once("did-finish-load", contentReady) + win.once("closed", () => { + reveal.dispatch({ type: "window.closed" }) + revealDrivers.delete(win) }) - win.once("ready-to-show", ready) - - if (process.platform === "linux") win.webContents.once("did-finish-load", ready) - win.once("closed", () => themeReady.delete(win)) return win } diff --git a/packages/desktop/src/main/windows/recovery.ts b/packages/desktop/src/main/windows/recovery.ts index 5e65db1368e..3735b0eba57 100644 --- a/packages/desktop/src/main/windows/recovery.ts +++ b/packages/desktop/src/main/windows/recovery.ts @@ -13,7 +13,15 @@ export const windowRecovery = Effect.gen(function* () { const logging = yield* DesktopLogging.Service const createUnresponsiveSampler = yield* unresponsiveSampler - function wireWindowRecovery(win: BrowserWindow, name: string, relaunch: () => void) { + function wireWindowRecovery( + win: BrowserWindow, + name: string, + options: { + readonly relaunch: () => void + /** Shows a window that is still hidden; the dialog is modal to it. */ + readonly reveal: () => void + }, + ) { let showing = false const sampler = createUnresponsiveSampler(win, name) @@ -33,7 +41,7 @@ export const windowRecovery = Effect.gen(function* () { if (action === "relaunch") { sampler.stopAndFlush() - relaunch() + options.relaunch() return false } @@ -51,6 +59,8 @@ export const windowRecovery = Effect.gen(function* () { showing = true try { + options.reveal() + while (!win.isDestroyed()) { const actions: { id: RecoveryAction; label: string }[] = wait ? [ diff --git a/packages/desktop/src/main/windows/reveal-machine.test.ts b/packages/desktop/src/main/windows/reveal-machine.test.ts new file mode 100644 index 00000000000..28770f581a4 --- /dev/null +++ b/packages/desktop/src/main/windows/reveal-machine.test.ts @@ -0,0 +1,158 @@ +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test" +import { + createRevealDriver, + initialRevealState, + REVEAL_TIMEOUT_MS, + transitionReveal, + type RevealCommand, + type RevealEvent, + type RevealReason, + type RevealState, +} from "./reveal-machine" + +// Folds events through the machine and keeps the commands of each step. +function replay(events: readonly RevealEvent[], from = initialRevealState(false)) { + return events.reduce<{ state: RevealState; commands: (readonly RevealCommand[])[] }>( + (result, event) => { + const next = transitionReveal(result.state, event) + + return { state: next.state, commands: [...result.commands, next.commands] } + }, + { state: from, commands: [] }, + ) +} + +const shown = (reason: RevealReason): RevealCommand[] => [{ type: "cancel-timeout" }, { type: "show", reason }] + +const hidden = { + loading: [], + "content-ready": [{ type: "content.ready" }], + "theme-ready": [{ type: "theme.ready" }], +} satisfies Record + +describe("window reveal", () => { + test("shows a window whose theme never arrives once the fallback expires", () => { + const result = replay([{ type: "content.ready" }, { type: "reveal.timed-out" }, { type: "theme.ready" }]) + + expect(result.state.status).toBe("shown") + expect(result.commands).toEqual([[], shown("timeout"), []]) + }) + + test.each(Object.entries(hidden))("shows a %s window before its recovery dialog", (_status, events) => { + const result = replay([ + ...events, + { type: "recovery.requested" }, + { type: "reveal.timed-out" }, + { type: "theme.ready" }, + ]) + + expect(result.state.status).toBe("shown") + expect(result.commands.slice(events.length)).toEqual([shown("recovery"), [], []]) + }) + + test.each([ + ["content first", [{ type: "content.ready" }, { type: "theme.ready" }]], + ["theme first", [{ type: "theme.ready" }, { type: "content.ready" }]], + ] satisfies [string, RevealEvent[]][])("waits for content and theme, %s", (_order, events) => { + expect(replay(events).commands).toEqual([[], shown("ready")]) + }) + + test("ignores the second content readiness Linux reports", () => { + const ready = transitionReveal(initialRevealState(false), { type: "content.ready" }).state + const again = transitionReveal(ready, { type: "content.ready" }) + + expect(again.state).toBe(ready) + expect(again.commands).toEqual([]) + expect(transitionReveal(again.state, { type: "theme.ready" }).commands).toEqual(shown("ready")) + }) + + test("never shows the early window again, including after a dev reload", () => { + const early = initialRevealState(true) + + const result = replay( + [ + { type: "content.ready" }, + { type: "theme.ready" }, + { type: "reveal.timed-out" }, + { type: "recovery.requested" }, + { type: "theme.ready" }, + ], + early, + ) + + expect(early.status).toBe("shown") + expect(result.state).toBe(early) + expect(result.commands.flat()).toEqual([]) + }) + + test.each(Object.entries(hidden))("cancels the fallback when a %s window closes", (_status, events) => { + const result = replay([...events, { type: "window.closed" }]) + + expect(result.state.status).toBe("closed") + expect(result.commands.at(-1)).toEqual([{ type: "cancel-timeout" }]) + }) + + test("ignores every event after the window closes", () => { + const closed = replay([{ type: "content.ready" }, { type: "theme.ready" }, { type: "window.closed" }]) + + const after = replay( + [ + { type: "content.ready" }, + { type: "theme.ready" }, + { type: "reveal.timed-out" }, + { type: "recovery.requested" }, + { type: "window.closed" }, + ], + closed.state, + ) + + expect(closed.commands.at(-1)).toEqual([]) + expect(after.state).toBe(closed.state) + expect(after.commands.flat()).toEqual([]) + }) +}) + +describe("window reveal driver", () => { + beforeEach(() => { + jest.useFakeTimers() + }) + + afterEach(() => { + jest.useRealTimers() + }) + + test("shows a hidden window once when the fallback expires", () => { + const shows: RevealReason[] = [] + const reveal = createRevealDriver({ early: false, show: (reason) => shows.push(reason) }) + + reveal.dispatch({ type: "content.ready" }) + jest.advanceTimersByTime(REVEAL_TIMEOUT_MS - 1) + expect(shows).toEqual([]) + + jest.advanceTimersByTime(1) + reveal.dispatch({ type: "theme.ready" }) + expect(shows).toEqual(["timeout"]) + }) + + test("does not fire the fallback after a ready reveal or a close", () => { + const shows: RevealReason[] = [] + const ready = createRevealDriver({ early: false, show: (reason) => shows.push(reason) }) + const closed = createRevealDriver({ early: false, show: (reason) => shows.push(reason) }) + + ready.dispatch({ type: "theme.ready" }) + ready.dispatch({ type: "content.ready" }) + closed.dispatch({ type: "window.closed" }) + jest.runOnlyPendingTimers() + + expect(shows).toEqual(["ready"]) + expect(jest.getTimerCount()).toBe(0) + }) + + test("arms no fallback for the early window", () => { + const shows: RevealReason[] = [] + createRevealDriver({ early: true, show: (reason) => shows.push(reason) }) + + expect(jest.getTimerCount()).toBe(0) + expect(shows).toEqual([]) + }) +}) diff --git a/packages/desktop/src/main/windows/reveal-machine.ts b/packages/desktop/src/main/windows/reveal-machine.ts new file mode 100644 index 00000000000..0afaa168100 --- /dev/null +++ b/packages/desktop/src/main/windows/reveal-machine.ts @@ -0,0 +1,99 @@ +/** How long a hidden window waits for its content and theme before it shows anyway. */ +export const REVEAL_TIMEOUT_MS = 3_000 + +export type RevealReason = "ready" | "timeout" | "recovery" + +/** + * A new window stays hidden until its content has loaded and the renderer has applied its theme, so it never + * flashes unthemed. The early window was shown before adoption and starts `shown`. + */ +export type RevealState = + | { readonly status: "loading" } + | { readonly status: "content-ready" } + | { readonly status: "theme-ready" } + | { readonly status: "shown" } + | { readonly status: "closed" } + +export type RevealEvent = + | { readonly type: "content.ready" } + | { readonly type: "theme.ready" } + | { readonly type: "reveal.timed-out" } + | { readonly type: "recovery.requested" } + | { readonly type: "window.closed" } + +export type RevealCommand = + | { readonly type: "show"; readonly reason: RevealReason } + | { readonly type: "cancel-timeout" } + +export type RevealTransition = { + readonly state: RevealState + readonly commands: readonly RevealCommand[] +} + +const LOADING: RevealState = Object.freeze({ status: "loading" }) + +const CONTENT_READY: RevealState = Object.freeze({ status: "content-ready" }) + +const THEME_READY: RevealState = Object.freeze({ status: "theme-ready" }) + +const SHOWN: RevealState = Object.freeze({ status: "shown" }) + +const CLOSED: RevealState = Object.freeze({ status: "closed" }) + +export function initialRevealState(early: boolean): RevealState { + return early ? SHOWN : LOADING +} + +export function transitionReveal(state: RevealState, event: RevealEvent): RevealTransition { + if (state.status === "closed") return unchanged(state) + + if (event.type === "window.closed") + return { state: CLOSED, commands: state.status === "shown" ? [] : [{ type: "cancel-timeout" }] } + + if (state.status === "shown") return unchanged(state) + + if (event.type === "reveal.timed-out") return show("timeout") + + // A recovery dialog is modal to the window, so the window has to be visible for the user to see it. + if (event.type === "recovery.requested") return show("recovery") + + if (event.type === "content.ready") { + if (state.status === "theme-ready") return show("ready") + + // Linux reports content readiness twice (`ready-to-show` and `did-finish-load`). + return state.status === "content-ready" ? unchanged(state) : { state: CONTENT_READY, commands: [] } + } + + if (state.status === "content-ready") return show("ready") + + return state.status === "theme-ready" ? unchanged(state) : { state: THEME_READY, commands: [] } +} + +function show(reason: RevealReason): RevealTransition { + return { state: SHOWN, commands: [{ type: "cancel-timeout" }, { type: "show", reason }] } +} + +function unchanged(state: RevealState): RevealTransition { + return { state, commands: [] } +} + +/** Runs one window's reveal machine and owns its fallback timer. */ +export function createRevealDriver(input: { readonly early: boolean; readonly show: (reason: RevealReason) => void }) { + const current = { state: initialRevealState(input.early) } + + const dispatch = (event: RevealEvent) => { + const next = transitionReveal(current.state, event) + current.state = next.state + next.commands.forEach(perform) + } + + const timer = input.early ? undefined : setTimeout(() => dispatch({ type: "reveal.timed-out" }), REVEAL_TIMEOUT_MS) + + const perform = (command: RevealCommand) => { + if (command.type === "cancel-timeout") return clearTimeout(timer) + + input.show(command.reason) + } + + return { dispatch } +}