mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-16 05:01:03 +03:00
fix(desktop): settle startup asset gate, plugin catalogs and first-launch onboarding through state machines (#62115)
This commit is contained in:
committed by
GitHub
Unverified
parent
10db139dc4
commit
6666acc12c
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createMainOnboardingState,
|
||||
selectOnboardingPending,
|
||||
transitionMainOnboarding,
|
||||
type MainOnboardingCommand,
|
||||
type MainOnboardingEvent,
|
||||
type MainOnboardingState,
|
||||
} from "./onboarding-machine"
|
||||
|
||||
const directory = "/Users/me/Documents/OpenCode"
|
||||
|
||||
// Folds events through the machine and keeps the commands of each step.
|
||||
function replay(events: readonly MainOnboardingEvent[], from: MainOnboardingState = createMainOnboardingState()) {
|
||||
return events.reduce<{ state: MainOnboardingState; commands: (readonly MainOnboardingCommand[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionMainOnboarding(result.state, event)
|
||||
|
||||
return { state: next.state, commands: [...result.commands, next.commands] }
|
||||
},
|
||||
{ state: from, commands: [] },
|
||||
)
|
||||
}
|
||||
|
||||
const fresh: MainOnboardingEvent = { type: "initialized", complete: false }
|
||||
|
||||
describe("first-launch onboarding in main", () => {
|
||||
test("creates the default project once when two windows finish together", () => {
|
||||
// On dev both windows passed the pending check before either recorded completion, so the project was created twice
|
||||
// and both windows opened a draft.
|
||||
const run = replay([
|
||||
fresh,
|
||||
{ type: "finish.requested", directory },
|
||||
{ type: "finish.requested", directory },
|
||||
{ type: "finish.succeeded", attempt: 1 },
|
||||
])
|
||||
|
||||
expect(run.commands).toEqual([
|
||||
[],
|
||||
[{ type: "make-directory", attempt: 1, directory }],
|
||||
[],
|
||||
[{ type: "persist-complete" }],
|
||||
])
|
||||
expect(run.state.status).toBe("completed")
|
||||
})
|
||||
|
||||
test("tells a window opened while another finishes not to onboard", () => {
|
||||
const finishing = replay([fresh, { type: "finish.requested", directory }]).state
|
||||
|
||||
expect(selectOnboardingPending(replay([fresh]).state)).toBe(true)
|
||||
expect(selectOnboardingPending(finishing)).toBe(false)
|
||||
})
|
||||
|
||||
test("releases the claim when creating the project fails, and ignores the failed attempt after a retry", () => {
|
||||
const run = replay([
|
||||
fresh,
|
||||
{ type: "finish.requested", directory },
|
||||
{ type: "finish.failed", attempt: 1 },
|
||||
{ type: "finish.requested", directory },
|
||||
{ type: "finish.succeeded", attempt: 1 },
|
||||
{ type: "finish.succeeded", attempt: 2 },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(2)).toEqual([
|
||||
[],
|
||||
[{ type: "make-directory", attempt: 2, directory }],
|
||||
[],
|
||||
[{ type: "persist-complete" }],
|
||||
])
|
||||
expect(run.state.status).toBe("completed")
|
||||
})
|
||||
|
||||
test("completes without a project when the window does not create one", () => {
|
||||
const run = replay([fresh, { type: "finish.requested", directory: null }])
|
||||
|
||||
expect(run.commands.at(-1)).toEqual([{ type: "persist-complete" }])
|
||||
expect(selectOnboardingPending(run.state)).toBe(false)
|
||||
})
|
||||
|
||||
test("does nothing on a launch that already onboarded", () => {
|
||||
const completed = replay([{ type: "initialized", complete: true }]).state
|
||||
const result = transitionMainOnboarding(completed, { type: "finish.requested", directory })
|
||||
|
||||
expect(selectOnboardingPending(completed)).toBe(false)
|
||||
expect(result.state).toBe(completed)
|
||||
expect(result.commands).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* First-launch onboarding as main sees it, for every window at once. The first window to finish claims the run before
|
||||
* it creates the default project, so a second window that finishes meanwhile creates nothing and opens no draft. A
|
||||
* failed run releases the claim for a retry.
|
||||
*/
|
||||
export type MainOnboardingState =
|
||||
/** Startup has not decided yet whether this is a first launch. */
|
||||
| { readonly status: "unknown" }
|
||||
| { readonly status: "pending"; readonly nextAttempt: number }
|
||||
| { readonly status: "finishing"; readonly attempt: number }
|
||||
| { readonly status: "completed" }
|
||||
|
||||
export type MainOnboardingEvent =
|
||||
| { readonly type: "initialized"; readonly complete: boolean }
|
||||
/** `directory` is the default project to create, or null when the window does not create one. */
|
||||
| { readonly type: "finish.requested"; readonly directory: string | null }
|
||||
| { readonly type: "finish.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "finish.failed"; readonly attempt: number }
|
||||
|
||||
export type MainOnboardingCommand =
|
||||
| { readonly type: "make-directory"; readonly attempt: number; readonly directory: string }
|
||||
/** Records that onboarding completed, so later launches skip it. */
|
||||
| { readonly type: "persist-complete" }
|
||||
|
||||
export type MainOnboardingTransition = {
|
||||
readonly state: MainOnboardingState
|
||||
readonly commands: readonly MainOnboardingCommand[]
|
||||
}
|
||||
|
||||
const UNKNOWN: MainOnboardingState = Object.freeze({ status: "unknown" })
|
||||
|
||||
const COMPLETED: MainOnboardingState = Object.freeze({ status: "completed" })
|
||||
|
||||
export function createMainOnboardingState(): MainOnboardingState {
|
||||
return UNKNOWN
|
||||
}
|
||||
|
||||
export function transitionMainOnboarding(
|
||||
state: MainOnboardingState,
|
||||
event: MainOnboardingEvent,
|
||||
): MainOnboardingTransition {
|
||||
switch (event.type) {
|
||||
case "initialized":
|
||||
if (state.status !== "unknown") return unchanged(state)
|
||||
|
||||
return { state: event.complete ? COMPLETED : { status: "pending", nextAttempt: 1 }, commands: [] }
|
||||
|
||||
case "finish.requested":
|
||||
// Another window already claimed the run, or it completed: this one creates nothing.
|
||||
if (state.status !== "pending") return unchanged(state)
|
||||
|
||||
if (event.directory === null) return { state: COMPLETED, commands: [{ type: "persist-complete" }] }
|
||||
|
||||
return {
|
||||
state: { status: "finishing", attempt: state.nextAttempt },
|
||||
commands: [{ type: "make-directory", attempt: state.nextAttempt, directory: event.directory }],
|
||||
}
|
||||
|
||||
case "finish.succeeded":
|
||||
if (state.status !== "finishing" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: COMPLETED, commands: [{ type: "persist-complete" }] }
|
||||
|
||||
case "finish.failed":
|
||||
if (state.status !== "finishing" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { status: "pending", nextAttempt: state.attempt + 1 }, commands: [] }
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a window should still run onboarding; false while another window's run is in flight. */
|
||||
export const selectOnboardingPending = (state: MainOnboardingState) => state.status === "pending"
|
||||
|
||||
function unchanged(state: MainOnboardingState): MainOnboardingTransition {
|
||||
return { state, commands: [] }
|
||||
}
|
||||
@@ -1,16 +1,39 @@
|
||||
import { app } from "electron"
|
||||
import { Effect, FileSystem, Option, Path } from "effect"
|
||||
import { Effect, Exit, FileSystem, Option, Path, Predicate } from "effect"
|
||||
import { scoped } from "../native/logging"
|
||||
import { hasExistingAppState } from "../storage/install-state"
|
||||
import { FIRST_LAUNCH_ONBOARDING_COMPLETE_KEY } from "../storage/keys"
|
||||
import { getStore } from "../storage/store"
|
||||
import { nativeT } from "../native/translations"
|
||||
import {
|
||||
createMainOnboardingState,
|
||||
selectOnboardingPending,
|
||||
transitionMainOnboarding,
|
||||
type MainOnboardingEvent,
|
||||
} from "./onboarding-machine"
|
||||
|
||||
const onboarding = { state: createMainOnboardingState() }
|
||||
|
||||
// Records completion at once; the caller runs the directory it is handed.
|
||||
const dispatch = (event: MainOnboardingEvent) => {
|
||||
const next = transitionMainOnboarding(onboarding.state, event)
|
||||
onboarding.state = next.state
|
||||
|
||||
if (next.commands.some((command) => command.type === "persist-complete"))
|
||||
getStore().set(FIRST_LAUNCH_ONBOARDING_COMPLETE_KEY, true)
|
||||
|
||||
return next.commands
|
||||
}
|
||||
|
||||
export const initializeFirstLaunchOnboarding = Effect.fn("Onboarding.initialize")(function* (userDataPath: string) {
|
||||
const store = getStore()
|
||||
const current = store.get(FIRST_LAUNCH_ONBOARDING_COMPLETE_KEY)
|
||||
|
||||
if (typeof current === "boolean") return current
|
||||
if (Predicate.isBoolean(current)) {
|
||||
dispatch({ type: "initialized", complete: current })
|
||||
|
||||
return current
|
||||
}
|
||||
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const path = yield* Path.Path
|
||||
@@ -28,24 +51,19 @@ export const initializeFirstLaunchOnboarding = Effect.fn("Onboarding.initialize"
|
||||
|
||||
const complete = hasExistingAppState(entries)
|
||||
store.set(FIRST_LAUNCH_ONBOARDING_COMPLETE_KEY, complete)
|
||||
dispatch({ type: "initialized", complete })
|
||||
|
||||
return complete
|
||||
})
|
||||
|
||||
export const isFirstLaunchOnboardingPending = Effect.fn("Onboarding.isPending")(function* () {
|
||||
const pending = getStore().get(FIRST_LAUNCH_ONBOARDING_COMPLETE_KEY) !== true
|
||||
const pending = selectOnboardingPending(onboarding.state)
|
||||
yield* scoped("onboarding", Effect.logInfo("first launch onboarding pending checked", { pending }))
|
||||
|
||||
return pending
|
||||
})
|
||||
|
||||
export const finishFirstLaunchOnboarding = Effect.fn("Onboarding.finish")(function* (createDefaultProject: boolean) {
|
||||
if (!(yield* isFirstLaunchOnboardingPending())) {
|
||||
yield* scoped("onboarding", Effect.logInfo("first launch onboarding already completed"))
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const path = yield* Path.Path
|
||||
|
||||
@@ -53,9 +71,29 @@ export const finishFirstLaunchOnboarding = Effect.fn("Onboarding.finish")(functi
|
||||
? path.join(app.getPath("documents"), nativeT("desktop.onboarding.defaultProject"))
|
||||
: null
|
||||
|
||||
if (defaultProject) yield* fs.makeDirectory(defaultProject, { recursive: true })
|
||||
// Claimed before the first await, so a second window finishing meanwhile neither creates the project nor opens a draft.
|
||||
const commands = dispatch({ type: "finish.requested", directory: defaultProject })
|
||||
const make = commands.find((command) => command.type === "make-directory")
|
||||
|
||||
if (commands.length === 0) {
|
||||
yield* scoped("onboarding", Effect.logInfo("first launch onboarding already completed"))
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
if (make) {
|
||||
const attempt = make.attempt
|
||||
yield* fs
|
||||
.makeDirectory(make.directory, { recursive: true })
|
||||
.pipe(
|
||||
Effect.onExit((exit) =>
|
||||
Effect.sync(() =>
|
||||
dispatch(Exit.isSuccess(exit) ? { type: "finish.succeeded", attempt } : { type: "finish.failed", attempt }),
|
||||
),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
getStore().set(FIRST_LAUNCH_ONBOARDING_COMPLETE_KEY, true)
|
||||
yield* scoped(
|
||||
"onboarding",
|
||||
Effect.logInfo("first launch onboarding completed", { createDefaultProject, defaultProject }),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
CATALOG_TIMEOUT_MS,
|
||||
createHostState,
|
||||
selectCatalogMessages,
|
||||
transitionHost,
|
||||
type HostCommand,
|
||||
type HostEndpoint,
|
||||
@@ -13,8 +15,8 @@ const a: HostEndpoint = { url: "http://127.0.0.1:4096", authorization: "Basic a"
|
||||
const b: HostEndpoint = { url: "http://127.0.0.1:4097", authorization: "Basic b" }
|
||||
|
||||
// Folds events through the machine and keeps the commands of each step.
|
||||
function replay(events: readonly HostEvent<string>[], from: HostState = createHostState()) {
|
||||
return events.reduce<{ state: HostState; commands: (readonly HostCommand<string>[])[] }>(
|
||||
function replay(events: readonly HostEvent<string, string>[], from: HostState<string> = createHostState("en")) {
|
||||
return events.reduce<{ state: HostState<string>; commands: (readonly HostCommand<string, string>[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionHost(result.state, event)
|
||||
|
||||
@@ -144,7 +146,7 @@ describe("plugin host menubar", () => {
|
||||
})
|
||||
|
||||
test("does not start following while the app quits, and drops a listing that lands during the quit", () => {
|
||||
const stopped = createHostState()
|
||||
const stopped = createHostState("en")
|
||||
|
||||
expect(transitionHost(stopped, { type: "started", endpoint: a, quitting: true }).state).toBe(stopped)
|
||||
|
||||
@@ -158,3 +160,121 @@ describe("plugin host menubar", () => {
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
const de = () => Promise.resolve({ default: { greeting: "Hallo" } })
|
||||
|
||||
const fr = () => Promise.resolve({ default: { greeting: "Bonjour" } })
|
||||
|
||||
// A built-in's catalog: English inline, the other locales loaded when the user picks them.
|
||||
const catalog = { en: { greeting: "Hello", farewell: "Bye" }, de, fr }
|
||||
|
||||
const reply = () => {}
|
||||
|
||||
const registered: HostEvent<string, string> = { type: "catalog.registered", owner: "plugin", catalog, reply }
|
||||
|
||||
const load = (attempt: number, loader: typeof de): HostCommand<string, string> => ({
|
||||
type: "load-catalog",
|
||||
owner: "plugin",
|
||||
attempt,
|
||||
load: loader,
|
||||
timeoutMs: CATALOG_TIMEOUT_MS,
|
||||
})
|
||||
|
||||
const cancelTimer: HostCommand<string, string> = { type: "cancel-catalog-timer", owner: "plugin" }
|
||||
|
||||
const ready: HostCommand<string, string> = { type: "resolve-catalog-ready", replies: [reply] }
|
||||
|
||||
const queue: HostCommand<string, string> = { type: "queue-menubar" }
|
||||
|
||||
describe("plugin host catalogs", () => {
|
||||
test("keeps the locale the user switched to while a plugin's first locale still loads", () => {
|
||||
const run = replay(
|
||||
[
|
||||
registered,
|
||||
{ type: "locale.changed", locale: "en" },
|
||||
// On dev the first load's late answer overwrote the English the switch had already applied.
|
||||
{ type: "catalog.loaded", owner: "plugin", attempt: 1, messages: { greeting: "Hallo" } },
|
||||
],
|
||||
createHostState("de"),
|
||||
)
|
||||
|
||||
expect(run.commands).toEqual([[load(1, de)], [cancelTimer, ready, queue], []])
|
||||
expect(selectCatalogMessages(run.state, "plugin")).toEqual(catalog.en)
|
||||
})
|
||||
|
||||
test("applies only the newest locale and publishes the menubar once it loaded", () => {
|
||||
const running = replay([registered]).state
|
||||
|
||||
const run = replay(
|
||||
[
|
||||
{ type: "locale.changed", locale: "de" },
|
||||
{ type: "locale.changed", locale: "fr" },
|
||||
// On dev a superseded load still rebuilt the menubar after the newer one settled.
|
||||
{ type: "catalog.loaded", owner: "plugin", attempt: 1, messages: { greeting: "Hallo" } },
|
||||
{ type: "catalog.loaded", owner: "plugin", attempt: 2, messages: { greeting: "Bonjour" } },
|
||||
],
|
||||
running,
|
||||
)
|
||||
|
||||
expect(run.commands).toEqual([[load(1, de)], [load(2, fr)], [], [cancelTimer, queue]])
|
||||
expect(selectCatalogMessages(run.state, "plugin")).toEqual({ greeting: "Bonjour", farewell: "Bye" })
|
||||
})
|
||||
|
||||
test("ignores the first load when the locale switches away and back", () => {
|
||||
const run = replay([
|
||||
registered,
|
||||
{ type: "locale.changed", locale: "de" },
|
||||
{ type: "locale.changed", locale: "fr" },
|
||||
{ type: "locale.changed", locale: "de" },
|
||||
{ type: "catalog.loaded", owner: "plugin", attempt: 1, messages: { greeting: "stale" } },
|
||||
{ type: "catalog.loaded", owner: "plugin", attempt: 3, messages: { greeting: "Hallo" } },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(-2)).toEqual([[], [cancelTimer, queue]])
|
||||
expect(selectCatalogMessages(run.state, "plugin").greeting).toBe("Hallo")
|
||||
})
|
||||
|
||||
test.each([
|
||||
["fails", { type: "catalog.failed", owner: "plugin", attempt: 1 }],
|
||||
["hangs", { type: "catalog.timed-out", owner: "plugin", attempt: 1 }],
|
||||
] satisfies [string, HostEvent<string, string>][])(
|
||||
"runs setup in English when a plugin's first locale %s",
|
||||
(_name, event) => {
|
||||
// On dev a loader that never settled held the plugin's setup forever.
|
||||
const run = replay([registered, event], createHostState("de"))
|
||||
|
||||
expect(run.commands.at(-1)).toEqual([cancelTimer, ready])
|
||||
expect(selectCatalogMessages(run.state, "plugin")).toEqual(catalog.en)
|
||||
},
|
||||
)
|
||||
|
||||
test("keeps a running plugin's copy until its locale loads, and falls back to English when it fails", () => {
|
||||
const loading = replay([registered, { type: "locale.changed", locale: "de" }]).state
|
||||
const failed = transitionHost(loading, { type: "catalog.failed", owner: "plugin", attempt: 1 })
|
||||
|
||||
expect(selectCatalogMessages(loading, "plugin")).toEqual(catalog.en)
|
||||
expect(failed.commands).toEqual([cancelTimer, queue])
|
||||
expect(selectCatalogMessages(failed.state, "plugin")).toEqual(catalog.en)
|
||||
})
|
||||
|
||||
test("lets setup go and drops a late load when the plugin stops while its locale loads", () => {
|
||||
const run = replay(
|
||||
[
|
||||
registered,
|
||||
{ type: "catalog.unregistered", owner: "plugin" },
|
||||
{ type: "catalog.loaded", owner: "plugin", attempt: 1, messages: { greeting: "Hallo" } },
|
||||
],
|
||||
createHostState("de"),
|
||||
)
|
||||
|
||||
expect(run.commands.slice(1)).toEqual([[cancelTimer, ready], []])
|
||||
expect(run.state.catalogs.size).toBe(0)
|
||||
})
|
||||
|
||||
test("keeps catalogs across a stop of the server follow", () => {
|
||||
const run = replay([registered, { type: "started", endpoint: a, ...live }, { type: "stopped" }])
|
||||
|
||||
expect(selectCatalogMessages(run.state, "plugin")).toEqual(catalog.en)
|
||||
expect(run.state.locale).toBe("en")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,28 @@
|
||||
import type { BuiltinCatalog } from "@opencode/plugin/gui/builtin"
|
||||
import type { Messages } from "@opencode/plugin/gui/main"
|
||||
import { Predicate } from "effect"
|
||||
|
||||
export const WATCH_RETRY_MS = 1_000
|
||||
|
||||
export const LIST_TIMEOUT_MS = 30_000
|
||||
|
||||
/** How long a locale's catalog may load before the plugin falls back to English. */
|
||||
export const CATALOG_TIMEOUT_MS = 5_000
|
||||
|
||||
export type HostCatalogLoader = () => Promise<{ readonly default: Messages }>
|
||||
|
||||
// A plugin instance's copy in the app locale. While a locale loads the instance keeps the copy it had; `ready` is the
|
||||
// instance's setup waiting for its first copy, and is undefined once the instance runs.
|
||||
export type HostCatalog =
|
||||
| {
|
||||
readonly status: "loading"
|
||||
readonly catalog: BuiltinCatalog | undefined
|
||||
readonly messages: Messages
|
||||
readonly attempt: number
|
||||
readonly ready: (() => void) | undefined
|
||||
}
|
||||
| { readonly status: "ready"; readonly catalog: BuiltinCatalog | undefined; readonly messages: Messages }
|
||||
|
||||
/** The app's own server as main reaches it. */
|
||||
export type HostEndpoint = {
|
||||
readonly url: string
|
||||
@@ -20,19 +41,25 @@ export type HostList =
|
||||
| { readonly status: "listing"; readonly attempt: number; readonly queued: boolean }
|
||||
|
||||
// `menubarQueued` is a menubar publish waiting for its microtask, in either phase: quitting keeps the menu as it is.
|
||||
export type HostState =
|
||||
| { readonly status: "stopped"; readonly nextAttempt: number; readonly menubarQueued: boolean }
|
||||
| {
|
||||
// Plugin instances run in either phase too, so their catalogs follow the app locale in both.
|
||||
type HostShared<Owner> = {
|
||||
readonly nextAttempt: number
|
||||
readonly menubarQueued: boolean
|
||||
readonly locale: string
|
||||
readonly catalogs: ReadonlyMap<Owner, HostCatalog>
|
||||
}
|
||||
|
||||
export type HostState<Owner = unknown> =
|
||||
| ({ readonly status: "stopped" } & HostShared<Owner>)
|
||||
| ({
|
||||
readonly status: "following"
|
||||
readonly nextAttempt: number
|
||||
readonly menubarQueued: boolean
|
||||
readonly endpoint: HostEndpoint | undefined
|
||||
readonly watch: HostWatch
|
||||
readonly list: HostList
|
||||
}
|
||||
} & HostShared<Owner>)
|
||||
|
||||
// `quitting` is the app lifecycle's answer when the event happened.
|
||||
export type HostEvent<Listing> =
|
||||
export type HostEvent<Listing, Owner = unknown> =
|
||||
| { readonly type: "started"; readonly endpoint: HostEndpoint | undefined; readonly quitting: boolean }
|
||||
| { readonly type: "resumed"; readonly endpoint: HostEndpoint | undefined; readonly quitting: boolean }
|
||||
| { readonly type: "stopped" }
|
||||
@@ -45,8 +72,20 @@ export type HostEvent<Listing> =
|
||||
| { readonly type: "list.timed-out"; readonly attempt: number; readonly quitting: boolean }
|
||||
| { readonly type: "menubar.scheduled" }
|
||||
| { readonly type: "menubar.flushed"; readonly quitting: boolean }
|
||||
| { readonly type: "locale.changed"; readonly locale: string }
|
||||
/** A plugin instance was created; `reply` lets its setup run once its copy is in the app locale. */
|
||||
| {
|
||||
readonly type: "catalog.registered"
|
||||
readonly owner: Owner
|
||||
readonly catalog: BuiltinCatalog | undefined
|
||||
readonly reply: () => void
|
||||
}
|
||||
| { readonly type: "catalog.unregistered"; readonly owner: Owner }
|
||||
| { readonly type: "catalog.loaded"; readonly owner: Owner; readonly attempt: number; readonly messages: Messages }
|
||||
| { readonly type: "catalog.failed"; readonly owner: Owner; readonly attempt: number }
|
||||
| { readonly type: "catalog.timed-out"; readonly owner: Owner; readonly attempt: number }
|
||||
|
||||
export type HostCommand<Listing> =
|
||||
export type HostCommand<Listing, Owner = unknown> =
|
||||
| { readonly type: "subscribe-credentials" }
|
||||
| { readonly type: "unsubscribe-credentials" }
|
||||
| { readonly type: "start-watch"; readonly attempt: number; readonly endpoint: HostEndpoint }
|
||||
@@ -63,20 +102,40 @@ export type HostCommand<Listing> =
|
||||
| { readonly type: "log-list-error"; readonly cause: unknown }
|
||||
| { readonly type: "queue-menubar" }
|
||||
| { readonly type: "publish-menubar" }
|
||||
| {
|
||||
readonly type: "load-catalog"
|
||||
readonly owner: Owner
|
||||
readonly attempt: number
|
||||
readonly load: HostCatalogLoader
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
| { readonly type: "cancel-catalog-timer"; readonly owner: Owner }
|
||||
| { readonly type: "resolve-catalog-ready"; readonly replies: readonly (() => void)[] }
|
||||
|
||||
export type HostTransition<Listing> = {
|
||||
readonly state: HostState
|
||||
readonly commands: readonly HostCommand<Listing>[]
|
||||
export type HostTransition<Listing, Owner = unknown> = {
|
||||
readonly state: HostState<Owner>
|
||||
readonly commands: readonly HostCommand<Listing, Owner>[]
|
||||
}
|
||||
|
||||
type Following = Extract<HostState, { status: "following" }>
|
||||
type Following<Owner> = Extract<HostState<Owner>, { status: "following" }>
|
||||
|
||||
export function createHostState(): HostState {
|
||||
return { status: "stopped", nextAttempt: 1, menubarQueued: false }
|
||||
export function createHostState<Owner = unknown>(locale: string): HostState<Owner> {
|
||||
return { status: "stopped", nextAttempt: 1, menubarQueued: false, locale, catalogs: new Map() }
|
||||
}
|
||||
|
||||
export function transitionHost<Listing>(state: HostState, event: HostEvent<Listing>): HostTransition<Listing> {
|
||||
export function transitionHost<Listing, Owner = unknown>(
|
||||
state: HostState<Owner>,
|
||||
event: HostEvent<Listing, Owner>,
|
||||
): HostTransition<Listing, Owner> {
|
||||
switch (event.type) {
|
||||
case "locale.changed":
|
||||
case "catalog.registered":
|
||||
case "catalog.unregistered":
|
||||
case "catalog.loaded":
|
||||
case "catalog.failed":
|
||||
case "catalog.timed-out":
|
||||
return transitionCatalogs(state, event)
|
||||
|
||||
case "menubar.scheduled":
|
||||
if (state.menubarQueued) return unchanged(state)
|
||||
|
||||
@@ -92,8 +151,8 @@ export function transitionHost<Listing>(state: HostState, event: HostEvent<Listi
|
||||
}
|
||||
|
||||
case "resumed": {
|
||||
const queued = transitionHost<Listing>(state, { type: "menubar.scheduled" })
|
||||
const started = transitionHost<Listing>(queued.state, { ...event, type: "started" })
|
||||
const queued = transitionHost<Listing, Owner>(state, { type: "menubar.scheduled" })
|
||||
const started = transitionHost<Listing, Owner>(queued.state, { ...event, type: "started" })
|
||||
|
||||
return { state: started.state, commands: [...queued.commands, ...started.commands] }
|
||||
}
|
||||
@@ -104,14 +163,7 @@ export function transitionHost<Listing>(state: HostState, event: HostEvent<Listi
|
||||
if (event.quitting) return unchanged(state)
|
||||
|
||||
return follow(
|
||||
{
|
||||
status: "following",
|
||||
nextAttempt: state.nextAttempt,
|
||||
menubarQueued: state.menubarQueued,
|
||||
endpoint: undefined,
|
||||
watch: IDLE_WATCH,
|
||||
list: IDLE_LIST,
|
||||
},
|
||||
{ ...state, status: "following", endpoint: undefined, watch: IDLE_WATCH, list: IDLE_LIST },
|
||||
event.endpoint,
|
||||
false,
|
||||
[{ type: "subscribe-credentials" }],
|
||||
@@ -121,8 +173,14 @@ export function transitionHost<Listing>(state: HostState, event: HostEvent<Listi
|
||||
if (state.status === "stopped") return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: "stopped", nextAttempt: state.nextAttempt, menubarQueued: state.menubarQueued },
|
||||
commands: [{ type: "unsubscribe-credentials" }, ...cancelled<Listing>(state)],
|
||||
state: {
|
||||
status: "stopped",
|
||||
nextAttempt: state.nextAttempt,
|
||||
menubarQueued: state.menubarQueued,
|
||||
locale: state.locale,
|
||||
catalogs: state.catalogs,
|
||||
},
|
||||
commands: [{ type: "unsubscribe-credentials" }, ...cancelled<Listing, Owner>(state)],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -196,7 +254,7 @@ export function transitionHost<Listing>(state: HostState, event: HostEvent<Listi
|
||||
}
|
||||
|
||||
/** Whether a watch started with `attempt` is still the one to run. */
|
||||
export function isCurrentHostWatch(state: HostState, attempt: number) {
|
||||
export function isCurrentHostWatch<Owner>(state: HostState<Owner>, attempt: number) {
|
||||
return state.status === "following" && state.watch.status === "streaming" && state.watch.attempt === attempt
|
||||
}
|
||||
|
||||
@@ -208,25 +266,25 @@ const IDLE_WATCH: HostWatch = Object.freeze({ status: "idle" })
|
||||
|
||||
const IDLE_LIST: HostList = Object.freeze({ status: "idle" })
|
||||
|
||||
function currentList(state: Following, attempt: number) {
|
||||
function currentList<Owner>(state: Following<Owner>, attempt: number) {
|
||||
return state.list.status === "listing" && state.list.attempt === attempt
|
||||
}
|
||||
|
||||
// Every credential change follows the server anew, as each connection and reconnect publishes one. A listing keeps
|
||||
// running only while the endpoint stays the same; one from a superseded endpoint never applies.
|
||||
function follow<Listing>(
|
||||
state: Following,
|
||||
function follow<Listing, Owner>(
|
||||
state: Following<Owner>,
|
||||
endpoint: HostEndpoint | undefined,
|
||||
quitting: boolean,
|
||||
before: readonly HostCommand<Listing>[] = [],
|
||||
): HostTransition<Listing> {
|
||||
before: readonly HostCommand<Listing, Owner>[] = [],
|
||||
): HostTransition<Listing, Owner> {
|
||||
const same = sameHostEndpoint(state.endpoint, endpoint)
|
||||
|
||||
if (quitting && same && state.watch.status === "idle" && state.list.status === "idle" && before.length === 0)
|
||||
return unchanged(state)
|
||||
const stopsList = quitting || !same
|
||||
|
||||
const commands: HostCommand<Listing>[] = [
|
||||
const commands: HostCommand<Listing, Owner>[] = [
|
||||
...before,
|
||||
...(state.watch.status === "idle" ? [] : [{ type: "cancel-watch" as const }]),
|
||||
...(stopsList && state.list.status !== "idle" ? [{ type: "cancel-list" as const }] : []),
|
||||
@@ -243,11 +301,11 @@ function follow<Listing>(
|
||||
}
|
||||
}
|
||||
|
||||
function list<Listing>(
|
||||
state: Following,
|
||||
function list<Listing, Owner>(
|
||||
state: Following<Owner>,
|
||||
endpoint: HostEndpoint,
|
||||
before: readonly HostCommand<Listing>[],
|
||||
): HostTransition<Listing> {
|
||||
before: readonly HostCommand<Listing, Owner>[],
|
||||
): HostTransition<Listing, Owner> {
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
@@ -257,24 +315,208 @@ function list<Listing>(
|
||||
}
|
||||
|
||||
// Ends the current listing and starts the queued one, if a change arrived meanwhile and the app is not quitting.
|
||||
function settleList<Listing>(
|
||||
state: Following,
|
||||
commands: readonly HostCommand<Listing>[],
|
||||
function settleList<Listing, Owner>(
|
||||
state: Following<Owner>,
|
||||
commands: readonly HostCommand<Listing, Owner>[],
|
||||
quitting: boolean,
|
||||
): HostTransition<Listing> {
|
||||
): HostTransition<Listing, Owner> {
|
||||
if (!quitting && state.list.status === "listing" && state.list.queued && state.endpoint)
|
||||
return list(state, state.endpoint, commands)
|
||||
|
||||
return { state: { ...state, list: IDLE_LIST }, commands }
|
||||
}
|
||||
|
||||
function cancelled<Listing>(state: Following): HostCommand<Listing>[] {
|
||||
function cancelled<Listing, Owner>(state: Following<Owner>): HostCommand<Listing, Owner>[] {
|
||||
return [
|
||||
...(state.watch.status === "idle" ? [] : [{ type: "cancel-watch" as const }]),
|
||||
...(state.list.status === "idle" ? [] : [{ type: "cancel-list" as const }]),
|
||||
]
|
||||
}
|
||||
|
||||
function unchanged<Listing>(state: HostState): HostTransition<Listing> {
|
||||
function unchanged<Listing, Owner>(state: HostState<Owner>): HostTransition<Listing, Owner> {
|
||||
return { state, commands: [] }
|
||||
}
|
||||
|
||||
/** The plugin instance's copy in the app locale; English while its locale loads for the first time. */
|
||||
export function selectCatalogMessages<Owner>(state: HostState<Owner>, owner: Owner): Messages {
|
||||
return state.catalogs.get(owner)?.messages ?? {}
|
||||
}
|
||||
|
||||
type CatalogEvent<Owner> = Extract<
|
||||
HostEvent<unknown, Owner>,
|
||||
{
|
||||
type:
|
||||
| "locale.changed"
|
||||
| "catalog.registered"
|
||||
| "catalog.unregistered"
|
||||
| "catalog.loaded"
|
||||
| "catalog.failed"
|
||||
| "catalog.timed-out"
|
||||
}
|
||||
>
|
||||
|
||||
// Each locale load carries an attempt, so a load a newer locale superseded (even one that switched back) never
|
||||
// applies. A load that fails or hangs leaves English, and the instance's setup waits for its first copy either way.
|
||||
function transitionCatalogs<Listing, Owner>(
|
||||
state: HostState<Owner>,
|
||||
event: CatalogEvent<Owner>,
|
||||
): HostTransition<Listing, Owner> {
|
||||
switch (event.type) {
|
||||
case "catalog.registered": {
|
||||
const source = catalogSource(event.catalog, state.locale)
|
||||
|
||||
if (source.kind === "sync")
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
catalogs: put(state.catalogs, event.owner, {
|
||||
status: "ready",
|
||||
catalog: event.catalog,
|
||||
messages: source.messages,
|
||||
}),
|
||||
},
|
||||
commands: [{ type: "resolve-catalog-ready", replies: [event.reply] }],
|
||||
}
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
nextAttempt: attempt + 1,
|
||||
catalogs: put(state.catalogs, event.owner, {
|
||||
status: "loading",
|
||||
catalog: event.catalog,
|
||||
messages: event.catalog?.en ?? {},
|
||||
attempt,
|
||||
ready: event.reply,
|
||||
}),
|
||||
},
|
||||
commands: [loadCatalog(event.owner, attempt, source.load)],
|
||||
}
|
||||
}
|
||||
|
||||
case "catalog.unregistered": {
|
||||
const entry = state.catalogs.get(event.owner)
|
||||
|
||||
if (!entry) return unchanged(state)
|
||||
const catalogs = new Map(state.catalogs)
|
||||
catalogs.delete(event.owner)
|
||||
|
||||
if (entry.status === "ready") return { state: { ...state, catalogs }, commands: [] }
|
||||
|
||||
return publishWhenLoaded(
|
||||
{
|
||||
state: { ...state, catalogs },
|
||||
commands: [{ type: "cancel-catalog-timer", owner: event.owner }, ...waiting<Listing, Owner>(entry)],
|
||||
},
|
||||
!entry.ready,
|
||||
)
|
||||
}
|
||||
|
||||
case "catalog.loaded":
|
||||
case "catalog.failed":
|
||||
case "catalog.timed-out": {
|
||||
const entry = state.catalogs.get(event.owner)
|
||||
|
||||
if (entry?.status !== "loading" || entry.attempt !== event.attempt) return unchanged(state)
|
||||
const english = entry.catalog?.en ?? {}
|
||||
|
||||
return publishWhenLoaded(
|
||||
{
|
||||
state: {
|
||||
...state,
|
||||
catalogs: put(state.catalogs, event.owner, {
|
||||
status: "ready",
|
||||
catalog: entry.catalog,
|
||||
messages: event.type === "catalog.loaded" ? { ...english, ...event.messages } : english,
|
||||
}),
|
||||
},
|
||||
commands: [{ type: "cancel-catalog-timer", owner: event.owner }, ...waiting<Listing, Owner>(entry)],
|
||||
},
|
||||
!entry.ready,
|
||||
)
|
||||
}
|
||||
|
||||
case "locale.changed": {
|
||||
if (event.locale === state.locale) return publishWhenLoaded({ state, commands: [] }, true)
|
||||
const commands: HostCommand<Listing, Owner>[] = []
|
||||
const replies: (() => void)[] = []
|
||||
const first = state.nextAttempt
|
||||
|
||||
const catalogs = new Map(
|
||||
[...state.catalogs].map(([owner, entry], index): [Owner, HostCatalog] => {
|
||||
const source = catalogSource(entry.catalog, event.locale)
|
||||
const ready = entry.status === "loading" ? entry.ready : undefined
|
||||
|
||||
if (source.kind === "async") {
|
||||
const attempt = first + index
|
||||
commands.push(loadCatalog(owner, attempt, source.load))
|
||||
|
||||
// A running instance keeps its copy until the new locale loads.
|
||||
return [owner, { status: "loading", catalog: entry.catalog, messages: entry.messages, attempt, ready }]
|
||||
}
|
||||
|
||||
if (entry.status === "loading") commands.push({ type: "cancel-catalog-timer", owner })
|
||||
|
||||
if (ready) replies.push(ready)
|
||||
|
||||
return [owner, { status: "ready", catalog: entry.catalog, messages: source.messages }]
|
||||
}),
|
||||
)
|
||||
|
||||
return publishWhenLoaded(
|
||||
{
|
||||
state: { ...state, nextAttempt: first + state.catalogs.size, locale: event.locale, catalogs },
|
||||
commands: [...commands, ...(replies.length ? [{ type: "resolve-catalog-ready" as const, replies }] : [])],
|
||||
},
|
||||
true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type CatalogSource =
|
||||
| { readonly kind: "sync"; readonly messages: Messages }
|
||||
| { readonly kind: "async"; readonly load: HostCatalogLoader }
|
||||
|
||||
function catalogSource(catalog: BuiltinCatalog | undefined, locale: string): CatalogSource {
|
||||
const english = catalog?.en ?? {}
|
||||
const source = locale === "en" ? undefined : catalog?.[locale]
|
||||
|
||||
if (!source) return { kind: "sync", messages: english }
|
||||
|
||||
if (Predicate.isFunction(source)) return { kind: "async", load: source }
|
||||
|
||||
return { kind: "sync", messages: { ...english, ...source } }
|
||||
}
|
||||
|
||||
function loadCatalog<Listing, Owner>(
|
||||
owner: Owner,
|
||||
attempt: number,
|
||||
load: HostCatalogLoader,
|
||||
): HostCommand<Listing, Owner> {
|
||||
return { type: "load-catalog", owner, attempt, load, timeoutMs: CATALOG_TIMEOUT_MS }
|
||||
}
|
||||
|
||||
/** Lets an instance's setup run once its first copy settled, or once it went away. */
|
||||
function waiting<Listing, Owner>(entry: HostCatalog): HostCommand<Listing, Owner>[] {
|
||||
return entry.status === "loading" && entry.ready ? [{ type: "resolve-catalog-ready", replies: [entry.ready] }] : []
|
||||
}
|
||||
|
||||
function put<Owner>(catalogs: ReadonlyMap<Owner, HostCatalog>, owner: Owner, entry: HostCatalog) {
|
||||
return new Map(catalogs).set(owner, entry)
|
||||
}
|
||||
|
||||
// The menubar shows running instances' copy, so it publishes once none of them still loads a locale. Instances whose
|
||||
// setup waits for their first copy contribute no items yet.
|
||||
function publishWhenLoaded<Listing, Owner>(
|
||||
next: HostTransition<Listing, Owner>,
|
||||
running: boolean,
|
||||
): HostTransition<Listing, Owner> {
|
||||
if (!running) return next
|
||||
|
||||
if ([...next.state.catalogs.values()].some((entry) => entry.status === "loading" && !entry.ready)) return next
|
||||
const queued = transitionHost<Listing, Owner>(next.state, { type: "menubar.scheduled" })
|
||||
|
||||
return { state: queued.state, commands: [...next.commands, ...queued.commands] }
|
||||
}
|
||||
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
type IpcSpec,
|
||||
type Log,
|
||||
type MainContext,
|
||||
type Messages,
|
||||
type OS,
|
||||
type Params,
|
||||
type PluginOptions,
|
||||
@@ -68,6 +67,7 @@ import {
|
||||
createHostState,
|
||||
isCurrentHostWatch,
|
||||
sameHostEndpoint,
|
||||
selectCatalogMessages,
|
||||
transitionHost,
|
||||
type HostCommand,
|
||||
type HostEndpoint,
|
||||
@@ -142,6 +142,8 @@ type HostResources = {
|
||||
watchTimer?: ReturnType<typeof setTimeout>
|
||||
list?: AbortController
|
||||
listTimer?: ReturnType<typeof setTimeout>
|
||||
/** Each plugin instance's catalog load timeout. */
|
||||
readonly catalogTimers: Map<Instance, ReturnType<typeof setTimeout>>
|
||||
}
|
||||
|
||||
/** An Ipc method with its spec erased: Ipcs of every spec share one table, and `call` runs the spec's codecs. */
|
||||
@@ -171,8 +173,6 @@ type Item = Parameters<MainContext["add"]>[1]
|
||||
|
||||
type Contribution = { readonly registry: string; readonly plugin: string; readonly value: Item }
|
||||
|
||||
type Translation = { readonly catalog?: BuiltinCatalog; messages: Messages }
|
||||
|
||||
const os = Match.value(process.platform).pipe(
|
||||
Match.when("darwin", () => "macos" as const),
|
||||
Match.when("win32", () => "windows" as const),
|
||||
@@ -228,8 +228,6 @@ export function createHost(input: {
|
||||
const skipped = new Map<string, string>()
|
||||
const entries = new Map<string, Contribution>()
|
||||
const ipcs = new Map<string, Provider>()
|
||||
// Each live instance's catalog and messages, so a locale change reaches them.
|
||||
const translations = new Set<Translation>()
|
||||
const closed = new Set<(win: BrowserWindow) => void>()
|
||||
let nextEntry = 0
|
||||
|
||||
@@ -429,12 +427,12 @@ export function createHost(input: {
|
||||
|
||||
// Follows the app's own server, as the TUI does: lists its plugins on each connection and each `plugin.updated`.
|
||||
// Every connection and reconnect of the server starts a new follow, so a new endpoint is followed at once.
|
||||
let following = createHostState()
|
||||
const resources: HostResources = {}
|
||||
let following = createHostState<Instance>(nativeLocale())
|
||||
const resources: HostResources = { catalogTimers: new Map() }
|
||||
|
||||
const quitting = () => isQuitting(input.appState())
|
||||
|
||||
const dispatch = (event: HostEvent<Listing>) => {
|
||||
const dispatch = (event: HostEvent<Listing, Instance>) => {
|
||||
const next = transitionHost(following, event)
|
||||
following = next.state
|
||||
// Each command runs on its own, so one that throws cannot keep the rest from running.
|
||||
@@ -445,7 +443,7 @@ export function createHost(input: {
|
||||
)
|
||||
}
|
||||
|
||||
const perform = (command: HostCommand<Listing>) => {
|
||||
const perform = (command: HostCommand<Listing, Instance>) => {
|
||||
switch (command.type) {
|
||||
case "subscribe-credentials":
|
||||
resources.unfollow = SidecarCredentials.onChange(() =>
|
||||
@@ -496,6 +494,28 @@ export function createHost(input: {
|
||||
refreshMenu()
|
||||
|
||||
return broadcast(new PluginMenubarItemsChanged({ items: listMenubarItems() }))
|
||||
case "load-catalog": {
|
||||
const owner = command.owner
|
||||
const attempt = command.attempt
|
||||
clearTimeout(resources.catalogTimers.get(owner))
|
||||
resources.catalogTimers.set(
|
||||
owner,
|
||||
setTimeout(() => dispatch({ type: "catalog.timed-out", owner, attempt }), command.timeoutMs),
|
||||
)
|
||||
|
||||
return void Promise.try(command.load).then(
|
||||
(module) => dispatch({ type: "catalog.loaded", owner, attempt, messages: module.default }),
|
||||
() => dispatch({ type: "catalog.failed", owner, attempt }),
|
||||
)
|
||||
}
|
||||
|
||||
case "cancel-catalog-timer":
|
||||
clearTimeout(resources.catalogTimers.get(command.owner))
|
||||
resources.catalogTimers.delete(command.owner)
|
||||
|
||||
return
|
||||
case "resolve-catalog-ready":
|
||||
return command.replies.forEach((reply) => reply())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,8 +553,8 @@ export function createHost(input: {
|
||||
)
|
||||
|
||||
const event = await readListing(endpoint, controller.signal).then(
|
||||
(listing): HostEvent<Listing> => ({ type: "list.succeeded", attempt, listing, quitting: quitting() }),
|
||||
(cause: unknown): HostEvent<Listing> => ({ type: "list.failed", attempt, cause, quitting: quitting() }),
|
||||
(listing): HostEvent<Listing, Instance> => ({ type: "list.succeeded", attempt, listing, quitting: quitting() }),
|
||||
(cause: unknown): HostEvent<Listing, Instance> => ({ type: "list.failed", attempt, cause, quitting: quitting() }),
|
||||
)
|
||||
|
||||
// Cancelled or timed out: the machine already moved on.
|
||||
@@ -672,17 +692,6 @@ export function createHost(input: {
|
||||
reserved: inventory.reserved,
|
||||
})
|
||||
|
||||
const resolveMessages = async (catalog?: BuiltinCatalog): Promise<Messages> => {
|
||||
const english = catalog?.en ?? {}
|
||||
const locale = nativeLocale()
|
||||
const source = locale === "en" ? undefined : catalog?.[locale]
|
||||
|
||||
if (!source) return english
|
||||
const loaded = Predicate.isFunction(source) ? (await source()).default : source
|
||||
|
||||
return { ...english, ...loaded }
|
||||
}
|
||||
|
||||
/** A loaded revision of the plugin's main code; each instance of it gets its own setup context. */
|
||||
const prepare =
|
||||
(id: string, loaded: Loaded): Revision =>
|
||||
@@ -695,11 +704,13 @@ export function createHost(input: {
|
||||
// Registered first, so it runs last: the instance's embeds go after everything else it contributed. They are
|
||||
// owned by the instance, so releasing them never touches a replacement's.
|
||||
contribute(() => embeds.releaseOwner(instance))
|
||||
const translation: Translation = { catalog: loaded.i18n, messages: loaded.i18n?.en ?? {} }
|
||||
translations.add(translation)
|
||||
contribute(() => {
|
||||
translations.delete(translation)
|
||||
})
|
||||
|
||||
// Setup waits for the instance's copy in the app locale; the host keeps it in that locale until the instance goes.
|
||||
const ready = new Promise<void>((reply) =>
|
||||
dispatch({ type: "catalog.registered", owner: instance, catalog: loaded.i18n, reply }),
|
||||
)
|
||||
|
||||
contribute(() => dispatch({ type: "catalog.unregistered", owner: instance }))
|
||||
// The instance's HostApis, each created on first read.
|
||||
const created: HostApis = {}
|
||||
|
||||
@@ -864,13 +875,14 @@ export function createHost(input: {
|
||||
list,
|
||||
provide,
|
||||
t: (key: string, params?: Params) =>
|
||||
formatNativeTemplate(translation.messages[key] ?? nativeMessage(key) ?? key, params),
|
||||
formatNativeTemplate(selectCatalogMessages(following, instance)[key] ?? nativeMessage(key) ?? key, params),
|
||||
plural: (key: string, count: number, params?: Params) => {
|
||||
const category = nativePluralCategory(count)
|
||||
const messages = selectCatalogMessages(following, instance)
|
||||
|
||||
const template =
|
||||
translation.messages[`${key}.${category}`] ??
|
||||
translation.messages[`${key}.other`] ??
|
||||
messages[`${key}.${category}`] ??
|
||||
messages[`${key}.other`] ??
|
||||
nativeMessage(`${key}.${category}`) ??
|
||||
nativeMessage(`${key}.other`) ??
|
||||
key
|
||||
@@ -880,9 +892,7 @@ export function createHost(input: {
|
||||
}
|
||||
|
||||
return {
|
||||
ready: resolveMessages(loaded.i18n).then((messages) => {
|
||||
translation.messages = messages
|
||||
}),
|
||||
ready,
|
||||
// A returned cleanup is a finalizer, as a server or TUI plugin's returned cleanup runs when it stops.
|
||||
setup: () =>
|
||||
Promise.resolve(loaded.setup(context)).then((cleanup) => {
|
||||
@@ -953,16 +963,7 @@ export function createHost(input: {
|
||||
getMainWindows().forEach(wire)
|
||||
onMainWindow(wire)
|
||||
|
||||
onNativeTranslations(() => {
|
||||
const locale = nativeLocale()
|
||||
void Promise.all(
|
||||
[...translations].map(async (translation) => {
|
||||
const messages = await resolveMessages(translation.catalog).catch(() => translation.catalog?.en ?? {})
|
||||
|
||||
if (nativeLocale() === locale) translation.messages = messages
|
||||
}),
|
||||
).then(scheduleMenubar)
|
||||
})
|
||||
onNativeTranslations(() => dispatch({ type: "locale.changed", locale: nativeLocale() }))
|
||||
|
||||
setMenubarProvider(() =>
|
||||
menubarItems().map((entry) => ({
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
type EarlyWindowCommand,
|
||||
type EarlyWindowEvent,
|
||||
} from "./early-machine"
|
||||
import { registerRendererProtocol } from "./protocol"
|
||||
import { cancelRendererAssetsServed, registerRendererProtocol } from "./protocol"
|
||||
import { persistedWindowIDs } from "./registry"
|
||||
import { loadWindow } from "./scheme"
|
||||
import { allowRendererPermissions, wireNavigationPolicy, wireRendererHeaders } from "./security"
|
||||
@@ -60,7 +60,10 @@ const perform = (command: EarlyWindowCommand<EarlyWindow>) => {
|
||||
return
|
||||
}
|
||||
|
||||
if (command.type === "quit") app.quit()
|
||||
if (command.type !== "quit") return
|
||||
// Nothing waits for the closed window's assets any more; the entry module sees the close at once.
|
||||
cancelRendererAssetsServed()
|
||||
app.quit()
|
||||
}
|
||||
|
||||
const displays = {
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createProtocolBurstState,
|
||||
isProtocolBurstSettled,
|
||||
transitionProtocolBurst,
|
||||
type ProtocolBurstCommand,
|
||||
type ProtocolBurstEvent,
|
||||
type ProtocolBurstState,
|
||||
} from "./protocol-machine"
|
||||
|
||||
const reply = () => {}
|
||||
|
||||
const wait: ProtocolBurstEvent = { type: "wait.requested", quietMs: 40, capMs: 400, reply }
|
||||
|
||||
const started: ProtocolBurstEvent = { type: "request.started" }
|
||||
|
||||
const finished: ProtocolBurstEvent = { type: "request.finished" }
|
||||
|
||||
const cap: ProtocolBurstCommand = { type: "start-cap-timer", delayMs: 400 }
|
||||
|
||||
const resolved: ProtocolBurstCommand[] = [{ type: "clear-timers" }, { type: "resolve", replies: [reply] }]
|
||||
|
||||
// Folds events through the machine and keeps the commands of each step.
|
||||
function replay(events: readonly ProtocolBurstEvent[], from: ProtocolBurstState = createProtocolBurstState()) {
|
||||
return events.reduce<{ state: ProtocolBurstState; commands: (readonly ProtocolBurstCommand[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionProtocolBurst(result.state, event)
|
||||
|
||||
return { state: next.state, commands: [...result.commands, next.commands] }
|
||||
},
|
||||
{ state: from, commands: [] },
|
||||
)
|
||||
}
|
||||
|
||||
describe("renderer asset burst", () => {
|
||||
test("waits a quiet window after a slow HTML read before the bundle loads", () => {
|
||||
// On dev the quiet window counted from the request's start, so an index.html read of 40 ms or more resolved the
|
||||
// moment it finished, before the renderer could ask for the scripts it names.
|
||||
const run = replay([wait, started, finished, started])
|
||||
|
||||
expect(run.commands).toEqual([
|
||||
[cap],
|
||||
[],
|
||||
[{ type: "start-quiet-timer", attempt: 1, delayMs: 40 }],
|
||||
[{ type: "cancel-quiet-timer" }],
|
||||
])
|
||||
expect(run.state.status).toBe("serving")
|
||||
})
|
||||
|
||||
test("settles once the last wave of requests has been quiet", () => {
|
||||
const run = replay([
|
||||
wait,
|
||||
started,
|
||||
finished,
|
||||
started,
|
||||
started,
|
||||
finished,
|
||||
finished,
|
||||
{ type: "quiet.elapsed", attempt: 2 },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(-2)).toEqual([[{ type: "start-quiet-timer", attempt: 2, delayMs: 40 }], resolved])
|
||||
expect(isProtocolBurstSettled(run.state)).toBe(true)
|
||||
})
|
||||
|
||||
test("ignores the quiet timer of a window a new request interrupted", () => {
|
||||
const quiet = replay([wait, started, finished, started, finished]).state
|
||||
const stale = transitionProtocolBurst(quiet, { type: "quiet.elapsed", attempt: 1 })
|
||||
|
||||
expect(stale.state).toBe(quiet)
|
||||
expect(stale.commands).toEqual([])
|
||||
})
|
||||
|
||||
test("starts from where the burst stands when the wait begins", () => {
|
||||
expect(replay([started, wait]).state).toMatchObject({ status: "serving", inflight: 1 })
|
||||
expect(replay([started, finished, wait]).commands.at(-1)).toEqual([
|
||||
cap,
|
||||
{ type: "start-quiet-timer", attempt: 1, delayMs: 40 },
|
||||
])
|
||||
expect(replay([wait]).state.status).toBe("awaiting-first")
|
||||
})
|
||||
|
||||
test.each([
|
||||
["the renderer never asks", [wait]],
|
||||
["the burst never goes quiet", [wait, started]],
|
||||
["the quiet window never elapses", [wait, started, finished]],
|
||||
] satisfies [string, ProtocolBurstEvent[]][])("loads the bundle at the cap when %s", (_name, events) => {
|
||||
const run = replay([...events, { type: "cap.elapsed" }])
|
||||
|
||||
expect(run.commands.at(-1)).toEqual(resolved)
|
||||
expect(isProtocolBurstSettled(run.state)).toBe(true)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["waiting for the first request", [wait]],
|
||||
["serving", [wait, started]],
|
||||
["quiet", [wait, started, finished]],
|
||||
] satisfies [string, ProtocolBurstEvent[]][])(
|
||||
"stops waiting at once when the first window closes while %s",
|
||||
(_name, events) => {
|
||||
// On dev a 5 ms poll kept running until the cap after the window closed.
|
||||
const run = replay([...events, { type: "cancelled" }])
|
||||
|
||||
expect(run.commands.at(-1)).toEqual(resolved)
|
||||
expect(isProtocolBurstSettled(run.state)).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
test("stops tracking requests once settled and answers a late wait at once", () => {
|
||||
const settled = replay([wait, { type: "cap.elapsed" }]).state
|
||||
const late = () => {}
|
||||
|
||||
expect(transitionProtocolBurst(settled, started).state).toBe(settled)
|
||||
expect(transitionProtocolBurst(settled, finished).state).toBe(settled)
|
||||
expect(transitionProtocolBurst(settled, { type: "quiet.elapsed", attempt: 1 }).commands).toEqual([])
|
||||
expect(transitionProtocolBurst(settled, { ...wait, reply: late }).commands).toEqual([
|
||||
{ type: "resolve", replies: [late] },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* The first renderer's burst of asset requests, which the entry module waits out before it evaluates the main bundle
|
||||
* on the thread that serves them. The burst is answered once no request has been in flight for `quietMs` after the
|
||||
* last one finished, or `capMs` after the wait began. Once settled, requests are no longer tracked.
|
||||
*/
|
||||
export type ProtocolBurstState =
|
||||
/** Nobody waits yet; requests are counted so a wait can start from where the burst stands. */
|
||||
| { readonly status: "idle"; readonly inflight: number; readonly served: boolean }
|
||||
/** The renderer has not asked for anything yet; only the cap ends the wait. */
|
||||
| { readonly status: "awaiting-first"; readonly quietMs: number; readonly replies: readonly (() => void)[] }
|
||||
| {
|
||||
readonly status: "serving"
|
||||
readonly inflight: number
|
||||
readonly quietMs: number
|
||||
readonly attempt: number
|
||||
readonly replies: readonly (() => void)[]
|
||||
}
|
||||
/** Every request finished; the quiet timer `attempt` runs. */
|
||||
| {
|
||||
readonly status: "quiet"
|
||||
readonly quietMs: number
|
||||
readonly attempt: number
|
||||
readonly replies: readonly (() => void)[]
|
||||
}
|
||||
| { readonly status: "settled" }
|
||||
|
||||
export type ProtocolBurstEvent =
|
||||
| { readonly type: "wait.requested"; readonly quietMs: number; readonly capMs: number; readonly reply: () => void }
|
||||
| { readonly type: "request.started" }
|
||||
| { readonly type: "request.finished" }
|
||||
| { readonly type: "quiet.elapsed"; readonly attempt: number }
|
||||
| { readonly type: "cap.elapsed" }
|
||||
/** The first window closed, so the app quits and nothing waits for its assets. */
|
||||
| { readonly type: "cancelled" }
|
||||
|
||||
export type ProtocolBurstCommand =
|
||||
| { readonly type: "start-cap-timer"; readonly delayMs: number }
|
||||
| { readonly type: "start-quiet-timer"; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "cancel-quiet-timer" }
|
||||
| { readonly type: "clear-timers" }
|
||||
| { readonly type: "resolve"; readonly replies: readonly (() => void)[] }
|
||||
|
||||
export type ProtocolBurstTransition = {
|
||||
readonly state: ProtocolBurstState
|
||||
readonly commands: readonly ProtocolBurstCommand[]
|
||||
}
|
||||
|
||||
const SETTLED: ProtocolBurstState = Object.freeze({ status: "settled" })
|
||||
|
||||
export function createProtocolBurstState(): ProtocolBurstState {
|
||||
return { status: "idle", inflight: 0, served: false }
|
||||
}
|
||||
|
||||
export function transitionProtocolBurst(state: ProtocolBurstState, event: ProtocolBurstEvent): ProtocolBurstTransition {
|
||||
if (state.status === "settled")
|
||||
return event.type === "wait.requested"
|
||||
? unchanged(state, [{ type: "resolve", replies: [event.reply] }])
|
||||
: unchanged(state)
|
||||
|
||||
if (state.status === "idle") return idle(state, event)
|
||||
|
||||
switch (event.type) {
|
||||
case "wait.requested":
|
||||
return to({ ...state, replies: [...state.replies, event.reply] })
|
||||
|
||||
case "cap.elapsed":
|
||||
case "cancelled":
|
||||
return settle(state.replies)
|
||||
|
||||
case "request.started":
|
||||
if (state.status === "serving") return to({ ...state, inflight: state.inflight + 1 })
|
||||
|
||||
return {
|
||||
state: {
|
||||
status: "serving",
|
||||
inflight: 1,
|
||||
quietMs: state.quietMs,
|
||||
attempt: state.status === "quiet" ? state.attempt : 0,
|
||||
replies: state.replies,
|
||||
},
|
||||
commands: state.status === "quiet" ? [{ type: "cancel-quiet-timer" }] : [],
|
||||
}
|
||||
|
||||
case "request.finished":
|
||||
if (state.status !== "serving") return unchanged(state)
|
||||
|
||||
if (state.inflight > 1) return to({ ...state, inflight: state.inflight - 1 })
|
||||
|
||||
// The quiet window starts when the last request finished, not when it started: a slow read of the HTML leaves
|
||||
// the renderer no time yet to ask for the scripts it names.
|
||||
return quiet(state.quietMs, state.attempt + 1, state.replies)
|
||||
|
||||
case "quiet.elapsed":
|
||||
if (state.status !== "quiet" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return settle(state.replies)
|
||||
}
|
||||
}
|
||||
|
||||
function idle(
|
||||
state: Extract<ProtocolBurstState, { status: "idle" }>,
|
||||
event: ProtocolBurstEvent,
|
||||
): ProtocolBurstTransition {
|
||||
switch (event.type) {
|
||||
case "request.started":
|
||||
return to({ ...state, inflight: state.inflight + 1 })
|
||||
|
||||
case "request.finished":
|
||||
if (state.inflight === 0) return unchanged(state)
|
||||
|
||||
return to({ ...state, inflight: state.inflight - 1, served: true })
|
||||
|
||||
case "cancelled":
|
||||
return to(SETTLED)
|
||||
|
||||
case "wait.requested": {
|
||||
const cap: ProtocolBurstCommand = { type: "start-cap-timer", delayMs: event.capMs }
|
||||
|
||||
if (state.inflight > 0)
|
||||
return {
|
||||
state: {
|
||||
status: "serving",
|
||||
inflight: state.inflight,
|
||||
quietMs: event.quietMs,
|
||||
attempt: 0,
|
||||
replies: [event.reply],
|
||||
},
|
||||
commands: [cap],
|
||||
}
|
||||
|
||||
if (state.served) {
|
||||
const next = quiet(event.quietMs, 1, [event.reply])
|
||||
|
||||
return { state: next.state, commands: [cap, ...next.commands] }
|
||||
}
|
||||
|
||||
return {
|
||||
state: { status: "awaiting-first", quietMs: event.quietMs, replies: [event.reply] },
|
||||
commands: [cap],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return unchanged(state)
|
||||
}
|
||||
|
||||
function quiet(quietMs: number, attempt: number, replies: readonly (() => void)[]): ProtocolBurstTransition {
|
||||
return {
|
||||
state: { status: "quiet", quietMs, attempt, replies },
|
||||
commands: [{ type: "start-quiet-timer", attempt, delayMs: quietMs }],
|
||||
}
|
||||
}
|
||||
|
||||
function settle(replies: readonly (() => void)[]): ProtocolBurstTransition {
|
||||
return { state: SETTLED, commands: [{ type: "clear-timers" }, { type: "resolve", replies }] }
|
||||
}
|
||||
|
||||
function to(state: ProtocolBurstState): ProtocolBurstTransition {
|
||||
return { state, commands: [] }
|
||||
}
|
||||
|
||||
function unchanged(state: ProtocolBurstState, commands: readonly ProtocolBurstCommand[] = []): ProtocolBurstTransition {
|
||||
return { state, commands }
|
||||
}
|
||||
|
||||
/** Requests after the burst settled are not tracked. */
|
||||
export const isProtocolBurstSettled = (state: ProtocolBurstState) => state.status === "settled"
|
||||
@@ -2,6 +2,13 @@ import { net, protocol } from "electron"
|
||||
import path from "node:path"
|
||||
import { pathToFileURL } from "node:url"
|
||||
import { documentPolicyHeader, jsCallStacksDocumentPolicy } from "./headers"
|
||||
import {
|
||||
createProtocolBurstState,
|
||||
isProtocolBurstSettled,
|
||||
transitionProtocolBurst,
|
||||
type ProtocolBurstCommand,
|
||||
type ProtocolBurstEvent,
|
||||
} from "./protocol-machine"
|
||||
import { rendererHost, rendererProtocol } from "./scheme"
|
||||
|
||||
/** What a renderer protocol problem is about: the request, and the file or failure behind it. */
|
||||
@@ -23,45 +30,71 @@ export function setProtocolReporter(reporter: ProtocolReport) {
|
||||
report = reporter
|
||||
}
|
||||
|
||||
// Requests in flight and when the last one arrived. The entry module holds the main bundle back
|
||||
// until the renderer's initial burst of asset requests has been answered, because this handler
|
||||
// runs on the main thread and a 100 ms module evaluation would otherwise sit between the renderer
|
||||
// and its HTML.
|
||||
let inflight = 0
|
||||
// The entry module holds the main bundle back until the renderer's initial burst of asset requests
|
||||
// has been answered, because this handler runs on the main thread and a 100 ms module evaluation
|
||||
// would otherwise sit between the renderer and its HTML.
|
||||
const burst = { state: createProtocolBurstState() }
|
||||
|
||||
let served = 0
|
||||
/** The burst's cap and quiet-window timers; the machine says when each starts and stops. */
|
||||
type BurstTimers = { cap?: ReturnType<typeof setTimeout>; quiet?: ReturnType<typeof setTimeout> }
|
||||
|
||||
let lastRequest = 0
|
||||
const timers: BurstTimers = {}
|
||||
|
||||
const dispatch = (event: ProtocolBurstEvent) => {
|
||||
const next = transitionProtocolBurst(burst.state, event)
|
||||
burst.state = next.state
|
||||
next.commands.forEach(perform)
|
||||
}
|
||||
|
||||
const perform = (command: ProtocolBurstCommand) => {
|
||||
switch (command.type) {
|
||||
case "start-cap-timer":
|
||||
clearTimeout(timers.cap)
|
||||
timers.cap = setTimeout(() => dispatch({ type: "cap.elapsed" }), command.delayMs)
|
||||
|
||||
return
|
||||
case "start-quiet-timer":
|
||||
clearTimeout(timers.quiet)
|
||||
timers.quiet = setTimeout(() => dispatch({ type: "quiet.elapsed", attempt: command.attempt }), command.delayMs)
|
||||
|
||||
return
|
||||
case "cancel-quiet-timer":
|
||||
clearTimeout(timers.quiet)
|
||||
timers.quiet = undefined
|
||||
|
||||
return
|
||||
case "clear-timers":
|
||||
clearTimeout(timers.cap)
|
||||
clearTimeout(timers.quiet)
|
||||
timers.cap = undefined
|
||||
timers.quiet = undefined
|
||||
|
||||
return
|
||||
case "resolve":
|
||||
return command.replies.forEach((reply) => reply())
|
||||
}
|
||||
}
|
||||
|
||||
export function rendererAssetsServed(options: { quietMs: number; capMs: number }) {
|
||||
const start = Date.now()
|
||||
return new Promise<void>((reply) => dispatch({ type: "wait.requested", ...options, reply }))
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
const check = () => {
|
||||
const now = Date.now()
|
||||
|
||||
if (now - start >= options.capMs) return resolve()
|
||||
|
||||
if (served > 0 && inflight === 0 && now - lastRequest >= options.quietMs) return resolve()
|
||||
setTimeout(check, 5)
|
||||
}
|
||||
|
||||
check()
|
||||
})
|
||||
/** The first window closed before the bundle loaded: the app quits, so nothing waits for its assets. */
|
||||
export function cancelRendererAssetsServed() {
|
||||
dispatch({ type: "cancelled" })
|
||||
}
|
||||
|
||||
export function registerRendererProtocol(rendererRoot: string) {
|
||||
if (protocol.isProtocolHandled(rendererProtocol)) return
|
||||
|
||||
protocol.handle(rendererProtocol, async (request) => {
|
||||
inflight++
|
||||
lastRequest = Date.now()
|
||||
if (isProtocolBurstSettled(burst.state)) return serve(request, rendererRoot)
|
||||
dispatch({ type: "request.started" })
|
||||
|
||||
try {
|
||||
return await serve(request, rendererRoot)
|
||||
} finally {
|
||||
inflight--
|
||||
served++
|
||||
dispatch({ type: "request.finished" })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
selectSplashDeep,
|
||||
selectStartupFailure,
|
||||
selectStartupLocale,
|
||||
selectStartupRevealed,
|
||||
transitionStartup,
|
||||
type StartupEffect,
|
||||
type StartupEvent,
|
||||
@@ -119,6 +120,7 @@ export function DesktopApp(props: { api: ElectronAPI; version: string }) {
|
||||
api={props.api}
|
||||
initialUrl={initialUrl}
|
||||
pending={selectFirstLaunch(startup.state())}
|
||||
revealed={selectStartupRevealed(startup.state())}
|
||||
dispatch={startup.dispatch}
|
||||
/>
|
||||
<DesktopEffects api={props.api} />
|
||||
|
||||
@@ -1,64 +1,147 @@
|
||||
import { ServerConnection, useCurrentRoute, useGlobal, useServers, useTabs } from "@opencode/app/desktop"
|
||||
import { onMount } from "solid-js"
|
||||
import { ServerConnection, useCurrentRoute, useGlobal, useLanguage, useServers, useTabs } from "@opencode/app/desktop"
|
||||
import { showToast } from "@opencode/ui/toast"
|
||||
import { createEffect, createSignal, onCleanup, untrack } from "solid-js"
|
||||
import type { ElectronAPI } from "../api-types"
|
||||
import type { StartupEvent } from "../startup/machine"
|
||||
import {
|
||||
createOnboardingState,
|
||||
selectOnboardingWaiting,
|
||||
transitionOnboarding,
|
||||
type OnboardingEffect,
|
||||
type OnboardingEvent,
|
||||
} from "./machine"
|
||||
|
||||
export function DesktopFirstLaunchOnboarding(props: {
|
||||
api: ElectronAPI
|
||||
initialUrl: string
|
||||
pending: boolean
|
||||
/** Startup already shows the app. */
|
||||
revealed: boolean
|
||||
dispatch: (event: StartupEvent) => void
|
||||
}) {
|
||||
const server = useServers()
|
||||
const global = useGlobal()
|
||||
const tabs = useTabs()
|
||||
const route = useCurrentRoute()
|
||||
const language = useLanguage()
|
||||
const sidecar = ServerConnection.Key.make("sidecar")
|
||||
|
||||
// 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 }),
|
||||
)
|
||||
})
|
||||
type Draft = Awaited<ReturnType<typeof tabs.newDraft>>
|
||||
|
||||
async function runFirstLaunchOnboarding() {
|
||||
await Promise.all([tabs.ready.promise, tabs.recentReady.promise].map((p) => p ?? Promise.resolve()))
|
||||
// Read once: the window runs onboarding or it does not.
|
||||
const [state, setState] = createSignal(createOnboardingState(untrack(() => props.pending)))
|
||||
// Events an effect raises wait until every effect of the event before them ran.
|
||||
const queue: OnboardingEvent<Draft>[] = []
|
||||
|
||||
const shouldTrigger =
|
||||
props.initialUrl === "/" &&
|
||||
route().type === "home" &&
|
||||
tabs.store.length === 0 &&
|
||||
server.list.every(ServerConnection.builtin)
|
||||
const revealed = () => untrack(() => props.revealed)
|
||||
const canOpenDraft = () => untrack(() => route().type === "home" && tabs.store.length === 0)
|
||||
|
||||
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 dispatch = (event: OnboardingEvent<Draft>) => {
|
||||
queue.push(event)
|
||||
|
||||
const directory = await props.api.finishFirstLaunchOnboarding(shouldTrigger)
|
||||
if (queue.length === 1) drain()
|
||||
}
|
||||
|
||||
if (!shouldTrigger || !directory) return
|
||||
const drain = () => {
|
||||
const event = queue[0]
|
||||
|
||||
console.info("[desktop-onboarding] starting first launch draft", { directory })
|
||||
const sidecar = ServerConnection.Key.make("sidecar")
|
||||
const ctx = global.serverCtx(sidecar)
|
||||
if (!event) return
|
||||
|
||||
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 }),
|
||||
])
|
||||
try {
|
||||
const next = transitionOnboarding(untrack(state), event)
|
||||
setState(next.state)
|
||||
// Each effect runs on its own, so one that throws cannot keep the rest from running.
|
||||
next.effects.forEach((effect) =>
|
||||
Promise.try(() => run(effect)).catch((error) =>
|
||||
console.error("[desktop-onboarding] effect failed", { effect: effect.type, error }),
|
||||
),
|
||||
)
|
||||
} finally {
|
||||
queue.shift()
|
||||
}
|
||||
|
||||
tabs.select(await tabs.newDraft({ server: sidecar, directory }))
|
||||
drain()
|
||||
}
|
||||
|
||||
const run = (effect: OnboardingEffect<Draft>) => {
|
||||
switch (effect.type) {
|
||||
case "finish-onboarding":
|
||||
console.info("[desktop-onboarding] first launch onboarding evaluated", {
|
||||
pending: true,
|
||||
shouldTrigger: effect.shouldTrigger,
|
||||
initialUrl: props.initialUrl,
|
||||
tabs: tabs.store.length,
|
||||
servers: server.list.map(ServerConnection.key),
|
||||
})
|
||||
|
||||
return void props.api.finishFirstLaunchOnboarding(effect.shouldTrigger).then(
|
||||
(directory) => dispatch({ type: "finish.succeeded", directory }),
|
||||
(error) => dispatch({ type: "finish.failed", error, revealed: revealed() }),
|
||||
)
|
||||
|
||||
case "seed-project": {
|
||||
console.info("[desktop-onboarding] starting first launch draft", { directory: effect.directory })
|
||||
const directory = effect.directory
|
||||
|
||||
// Load the initial provider/model state before the draft transition exposes the composer.
|
||||
return void Promise.try(() => {
|
||||
const ctx = global.serverCtx(sidecar)
|
||||
|
||||
if (!ctx) return
|
||||
|
||||
return Promise.all([
|
||||
ctx.projects.add(directory),
|
||||
ctx.data.location.provider.sync({ directory }),
|
||||
ctx.data.location.model.sync({ directory }),
|
||||
])
|
||||
}).then(
|
||||
() => dispatch({ type: "seed.succeeded", revealed: revealed(), canOpenDraft: canOpenDraft() }),
|
||||
(error) => dispatch({ type: "seed.failed", error, revealed: revealed() }),
|
||||
)
|
||||
}
|
||||
|
||||
case "open-draft":
|
||||
return void tabs.newDraft({ server: sidecar, directory: effect.directory }).then(
|
||||
(tab) => dispatch({ type: "draft.succeeded", tab, revealed: revealed() }),
|
||||
(error) => dispatch({ type: "draft.failed", error, revealed: revealed() }),
|
||||
)
|
||||
|
||||
case "select-draft":
|
||||
return tabs.select(effect.tab)
|
||||
|
||||
case "notify-settled":
|
||||
return props.dispatch({ type: "onboarding.settled" })
|
||||
|
||||
// A failure before the app shows reaches its recovery screen.
|
||||
case "fail-startup":
|
||||
return props.dispatch({ type: "startup.failed", error: effect.error })
|
||||
|
||||
case "show-error-toast":
|
||||
return showToast({
|
||||
variant: "error",
|
||||
title: language.t("common.requestFailed"),
|
||||
description: effect.error instanceof Error ? effect.error.message : String(effect.error),
|
||||
duration: 10_000,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
createEffect(() => {
|
||||
if (!selectOnboardingWaiting(state()) || !tabs.ready() || !tabs.recentReady()) return
|
||||
|
||||
dispatch({
|
||||
type: "tabs.hydrated",
|
||||
shouldTrigger: untrack(
|
||||
() =>
|
||||
props.initialUrl === "/" &&
|
||||
route().type === "home" &&
|
||||
tabs.store.length === 0 &&
|
||||
server.list.every(ServerConnection.builtin),
|
||||
),
|
||||
})
|
||||
})
|
||||
|
||||
onCleanup(() => dispatch({ type: "disposed" }))
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createOnboardingState,
|
||||
selectOnboardingWaiting,
|
||||
transitionOnboarding,
|
||||
type OnboardingEffect,
|
||||
type OnboardingEvent,
|
||||
type OnboardingState,
|
||||
} from "./machine"
|
||||
|
||||
type Tab = { readonly draftID: string }
|
||||
|
||||
const tab: Tab = { draftID: "draft" }
|
||||
|
||||
const directory = "/Users/me/Documents/OpenCode"
|
||||
|
||||
const error = new Error("timed out")
|
||||
|
||||
// Folds events through the machine and keeps the effects of each step.
|
||||
function replay(events: readonly OnboardingEvent<Tab>[], from: OnboardingState = createOnboardingState(true)) {
|
||||
return events.reduce<{ state: OnboardingState; effects: (readonly OnboardingEffect<Tab>[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionOnboarding(result.state, event)
|
||||
|
||||
return { state: next.state, effects: [...result.effects, next.effects] }
|
||||
},
|
||||
{ state: from, effects: [] },
|
||||
)
|
||||
}
|
||||
|
||||
// A fresh install on Home: main creates the default project.
|
||||
const finished: OnboardingEvent<Tab>[] = [
|
||||
{ type: "tabs.hydrated", shouldTrigger: true },
|
||||
{ type: "finish.succeeded", directory },
|
||||
]
|
||||
|
||||
describe("first-launch onboarding", () => {
|
||||
test("adds the default project and opens a draft in it behind the splash", () => {
|
||||
const run = replay([
|
||||
...finished,
|
||||
{ type: "seed.succeeded", revealed: false, canOpenDraft: true },
|
||||
{ type: "draft.succeeded", tab, revealed: false },
|
||||
])
|
||||
|
||||
expect(run.effects).toEqual([
|
||||
[{ type: "finish-onboarding", shouldTrigger: true }],
|
||||
[{ type: "seed-project", directory }],
|
||||
[{ type: "open-draft", directory }],
|
||||
[{ type: "select-draft", tab }, { type: "notify-settled" }],
|
||||
])
|
||||
expect(run.state.status).toBe("done")
|
||||
})
|
||||
|
||||
test("settles without a project when the window does not trigger onboarding", () => {
|
||||
const run = replay([
|
||||
{ type: "tabs.hydrated", shouldTrigger: false },
|
||||
{ type: "finish.succeeded", directory: null },
|
||||
])
|
||||
|
||||
expect(run.effects.at(-1)).toEqual([{ type: "notify-settled" }])
|
||||
expect(selectOnboardingWaiting(createOnboardingState(false))).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["the app shows while the project is added", [{ type: "seed.succeeded", revealed: true, canOpenDraft: true }]],
|
||||
[
|
||||
"a deep link opens a tab while the project is added",
|
||||
[{ type: "seed.succeeded", revealed: false, canOpenDraft: false }],
|
||||
],
|
||||
[
|
||||
"the app shows while the draft opens",
|
||||
[
|
||||
{ type: "seed.succeeded", revealed: false, canOpenDraft: true },
|
||||
{ type: "draft.succeeded", tab, revealed: true },
|
||||
],
|
||||
],
|
||||
] satisfies [string, OnboardingEvent<Tab>[]][])("does not navigate when %s", (_name, events) => {
|
||||
// On dev the run opened and selected the draft whenever it finished, taking the user away from what they opened.
|
||||
const run = replay([...finished, ...events])
|
||||
|
||||
expect(run.effects.at(-1)).toEqual([{ type: "notify-settled" }])
|
||||
expect(run.state.status).toBe("done")
|
||||
})
|
||||
|
||||
test.each([
|
||||
["main fails to finish", [{ type: "tabs.hydrated", shouldTrigger: true }], "finish.failed"],
|
||||
["adding the project fails", finished, "seed.failed"],
|
||||
[
|
||||
"opening the draft fails",
|
||||
[...finished, { type: "seed.succeeded", revealed: false, canOpenDraft: true }],
|
||||
"draft.failed",
|
||||
],
|
||||
] satisfies [string, OnboardingEvent<Tab>[], "finish.failed" | "seed.failed" | "draft.failed"][])(
|
||||
"shows the error page before the app shows, and a toast after, when %s",
|
||||
(_name, events, type) => {
|
||||
const before = replay(events).state
|
||||
|
||||
// On dev a failure after the hydration timeout showed the app replaced the working window with the error page.
|
||||
expect(transitionOnboarding(before, { type, error, revealed: false }).effects).toEqual([
|
||||
{ type: "fail-startup", error },
|
||||
])
|
||||
expect(transitionOnboarding(before, { type, error, revealed: true }).effects).toEqual([
|
||||
{ type: "show-error-toast", error },
|
||||
])
|
||||
},
|
||||
)
|
||||
|
||||
test.each([
|
||||
["waiting for tabs", []],
|
||||
["finishing", [{ type: "tabs.hydrated", shouldTrigger: true }]],
|
||||
["adding the project", finished],
|
||||
["opening the draft", [...finished, { type: "seed.succeeded", revealed: false, canOpenDraft: true }]],
|
||||
] satisfies [string, OnboardingEvent<Tab>[]][])(
|
||||
"ignores every late result once disposed while %s",
|
||||
(_name, events) => {
|
||||
// On dev the run kept going after the shell unmounted and selected tabs and dispatched into a torn-down owner.
|
||||
const disposed = replay([...events, { type: "disposed" }]).state
|
||||
|
||||
const late = replay(
|
||||
[
|
||||
{ type: "tabs.hydrated", shouldTrigger: true },
|
||||
{ type: "finish.succeeded", directory },
|
||||
{ type: "seed.succeeded", revealed: false, canOpenDraft: true },
|
||||
{ type: "draft.succeeded", tab, revealed: false },
|
||||
{ type: "seed.failed", error, revealed: false },
|
||||
],
|
||||
disposed,
|
||||
)
|
||||
|
||||
expect(disposed.status).toBe("disposed")
|
||||
expect(late.state).toBe(disposed)
|
||||
expect(late.effects.flat()).toEqual([])
|
||||
},
|
||||
)
|
||||
|
||||
test("ignores results for a step it is not in", () => {
|
||||
const finishing = replay([{ type: "tabs.hydrated", shouldTrigger: true }]).state
|
||||
|
||||
expect(transitionOnboarding(finishing, { type: "tabs.hydrated", shouldTrigger: false }).state).toBe(finishing)
|
||||
expect(transitionOnboarding(finishing, { type: "draft.succeeded", tab, revealed: false }).state).toBe(finishing)
|
||||
expect(transitionOnboarding(finishing, { type: "seed.failed", error, revealed: false }).state).toBe(finishing)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* First-launch onboarding in one window: once its tabs are restored it tells main whether to create the default
|
||||
* project, adds that project, then opens a draft in it. Startup keeps the splash up for it, but the hydration timeout
|
||||
* can show the app first. From then on the run never navigates, and a failure is a toast rather than the error page.
|
||||
*/
|
||||
export type OnboardingState =
|
||||
| { readonly status: "waiting" }
|
||||
| { readonly status: "finishing" }
|
||||
| { readonly status: "seeding"; readonly directory: string }
|
||||
| { readonly status: "drafting" }
|
||||
| { readonly status: "done" }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
// `revealed` is whether startup already showed the app when the result arrived; `canOpenDraft` whether the window still
|
||||
// shows Home with no tabs, as nothing such as a deep link opened one meanwhile.
|
||||
export type OnboardingEvent<Tab> =
|
||||
| { readonly type: "tabs.hydrated"; readonly shouldTrigger: boolean }
|
||||
| { readonly type: "finish.succeeded"; readonly directory: string | null }
|
||||
| { readonly type: "finish.failed"; readonly error: unknown; readonly revealed: boolean }
|
||||
| { readonly type: "seed.succeeded"; readonly revealed: boolean; readonly canOpenDraft: boolean }
|
||||
| { readonly type: "seed.failed"; readonly error: unknown; readonly revealed: boolean }
|
||||
| { readonly type: "draft.succeeded"; readonly tab: Tab; readonly revealed: boolean }
|
||||
| { readonly type: "draft.failed"; readonly error: unknown; readonly revealed: boolean }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type OnboardingEffect<Tab> =
|
||||
| { readonly type: "finish-onboarding"; readonly shouldTrigger: boolean }
|
||||
| { readonly type: "seed-project"; readonly directory: string }
|
||||
| { readonly type: "open-draft"; readonly directory: string }
|
||||
| { readonly type: "select-draft"; readonly tab: Tab }
|
||||
/** Startup may hide the splash. */
|
||||
| { readonly type: "notify-settled" }
|
||||
/** Startup shows the error page. */
|
||||
| { readonly type: "fail-startup"; readonly error: unknown }
|
||||
| { readonly type: "show-error-toast"; readonly error: unknown }
|
||||
|
||||
export type OnboardingTransition<Tab> = {
|
||||
readonly state: OnboardingState
|
||||
readonly effects: readonly OnboardingEffect<Tab>[]
|
||||
}
|
||||
|
||||
const DONE: OnboardingState = Object.freeze({ status: "done" })
|
||||
|
||||
const DISPOSED: OnboardingState = Object.freeze({ status: "disposed" })
|
||||
|
||||
export function createOnboardingState(pending: boolean): OnboardingState {
|
||||
return pending ? { status: "waiting" } : DONE
|
||||
}
|
||||
|
||||
// The run only moves forward, one step at a time, so each result names the step it ends and is ignored in any other.
|
||||
export function transitionOnboarding<Tab>(
|
||||
state: OnboardingState,
|
||||
event: OnboardingEvent<Tab>,
|
||||
): OnboardingTransition<Tab> {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
if (event.type === "disposed") return { state: DISPOSED, effects: [] }
|
||||
|
||||
switch (event.type) {
|
||||
case "tabs.hydrated":
|
||||
if (state.status !== "waiting") return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: "finishing" },
|
||||
effects: [{ type: "finish-onboarding", shouldTrigger: event.shouldTrigger }],
|
||||
}
|
||||
|
||||
case "finish.succeeded":
|
||||
if (state.status !== "finishing") return unchanged(state)
|
||||
|
||||
if (!event.directory) return settled()
|
||||
|
||||
return {
|
||||
state: { status: "seeding", directory: event.directory },
|
||||
effects: [{ type: "seed-project", directory: event.directory }],
|
||||
}
|
||||
|
||||
case "seed.succeeded":
|
||||
if (state.status !== "seeding") return unchanged(state)
|
||||
|
||||
// Once the app shows, the user may already be somewhere else: the project is added, but no draft opens.
|
||||
if (event.revealed || !event.canOpenDraft) return settled()
|
||||
|
||||
return { state: { status: "drafting" }, effects: [{ type: "open-draft", directory: state.directory }] }
|
||||
|
||||
case "draft.succeeded":
|
||||
if (state.status !== "drafting") return unchanged(state)
|
||||
|
||||
if (event.revealed) return settled()
|
||||
|
||||
return { state: DONE, effects: [{ type: "select-draft", tab: event.tab }, { type: "notify-settled" }] }
|
||||
|
||||
case "finish.failed":
|
||||
return state.status === "finishing" ? failed(event) : unchanged(state)
|
||||
|
||||
case "seed.failed":
|
||||
return state.status === "seeding" ? failed(event) : unchanged(state)
|
||||
|
||||
case "draft.failed":
|
||||
return state.status === "drafting" ? failed(event) : unchanged(state)
|
||||
}
|
||||
}
|
||||
|
||||
/** The step that waits for the window's tabs to be restored before the run starts. */
|
||||
export const selectOnboardingWaiting = (state: OnboardingState) => state.status === "waiting"
|
||||
|
||||
function settled<Tab>(): OnboardingTransition<Tab> {
|
||||
return { state: DONE, effects: [{ type: "notify-settled" }] }
|
||||
}
|
||||
|
||||
// Before the app shows, a failure reaches the error page as it did; afterwards it must not replace a working window.
|
||||
function failed<Tab>(event: { readonly error: unknown; readonly revealed: boolean }): OnboardingTransition<Tab> {
|
||||
return {
|
||||
state: DONE,
|
||||
effects: [
|
||||
event.revealed ? { type: "show-error-toast", error: event.error } : { type: "fail-startup", error: event.error },
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function unchanged<Tab>(state: OnboardingState): OnboardingTransition<Tab> {
|
||||
return { state, effects: [] }
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
selectSidecar,
|
||||
selectStartupFailure,
|
||||
selectStartupLocale,
|
||||
selectStartupRevealed,
|
||||
transitionStartup,
|
||||
type StartupEffect,
|
||||
type StartupEvent,
|
||||
@@ -214,11 +215,6 @@ describe("desktop startup", () => {
|
||||
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)
|
||||
@@ -229,6 +225,22 @@ describe("desktop startup", () => {
|
||||
expect(selectInterfaceMounted(result.state)).toBe(false)
|
||||
})
|
||||
|
||||
test.each([
|
||||
["fading in", [...mounted, { type: "tabs.ready" }]],
|
||||
["shown", [...mounted, { type: "tabs.ready" }, { type: "fade.timed-out" }]],
|
||||
] satisfies [string, StartupEvent[]][])(
|
||||
"keeps the app when a late failure arrives while it is %s",
|
||||
(_name, events) => {
|
||||
// On dev onboarding that failed after the hydration timeout showed the app replaced it with the error page.
|
||||
const before = replay(events)
|
||||
const result = transitionStartup(before.state, { type: "startup.failed", error: new Error("boom") })
|
||||
|
||||
expect(selectStartupRevealed(before.state)).toBe(true)
|
||||
expect(result.state).toBe(before.state)
|
||||
expect(selectInterfaceMounted(result.state)).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
test("stops its timer when the error boundary catches a render error", () => {
|
||||
const fresh = replay(
|
||||
[{ type: "theme.applied" }, { type: "boundary.tripped" }],
|
||||
|
||||
@@ -202,8 +202,6 @@ function step(state: StartupState, event: StartupEvent): StartupTransition {
|
||||
|
||||
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)
|
||||
|
||||
@@ -229,6 +227,9 @@ function step(state: StartupState, event: StartupEvent): StartupTransition {
|
||||
return unchanged(state)
|
||||
}
|
||||
|
||||
// Once the app shows, a late startup failure must not replace the working window with the error page.
|
||||
if (event.type === "startup.failed") return fail(state, { error: event.error })
|
||||
|
||||
if (event.type === "drawing.started")
|
||||
return state.drawing === "pending" ? to({ ...state, drawing: "running" }) : unchanged(state)
|
||||
|
||||
@@ -403,6 +404,11 @@ export function selectStartupFailure(state: StartupState) {
|
||||
return state.status === "failed" ? state.failure : undefined
|
||||
}
|
||||
|
||||
/** The splash is fading out or gone, so the user can see and use the app. */
|
||||
export function selectStartupRevealed(state: StartupState) {
|
||||
return state.status === "fading" || state.status === "revealed"
|
||||
}
|
||||
|
||||
export function selectInterfaceMounted(state: StartupState) {
|
||||
return state.status === "hydrating" || state.status === "fading" || state.status === "revealed"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user